gpt4 book ai didi

flutter - Flutter StatefulWidget 中的变量范围

转载 作者:IT王子 更新时间:2023-10-29 07:17:44 26 4
gpt4 key购买 nike

我正在尝试访问 build() 中的 moviesList,结果如下。真正的问题是什么?

flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following NoSuchMethodError was thrown building MyListScreen(dirty, state:
flutter: _MyListScreenState#21007):
flutter: The getter 'results' was called on null.
flutter: Receiver: null
flutter: Tried calling: results

代码片段如下:

class _MyListScreenState extends State<MyListScreen> {

MoviesList moviesList;

_getLatestMovies() {
APIService.getMoviesNowPlaying().then((response) {
setState(() {
final jsonData = json.decode(response.body);
moviesList = new MoviesList.fromJson(jsonData);
// moviesList(new MoviesList.fromJson(jsonData));

for (var i = 0; i < moviesList.results.length; i++) {
print(moviesList.results[i].title);
}
});
});
}

@override
initState() {
super.initState();
_getLatestMovies();
}

@override
Widget build(context) {
return Scaffold(
appBar: AppBar(
title: Text("View Title"),
),
body: ListView.separated(
padding: EdgeInsets.zero,
itemCount: moviesList.results.length,
itemBuilder: (context, index) {
// return ListTile(title: Text(moviesList.results[index].title));
},
separatorBuilder: (context, index) {
return Divider();
},
));
}
}

最佳答案

使用

itemCount: moviesList != null ? moviesList.results.length : 0,

您的 build()moviesList 初始化之前被调用,所以在这里我们首先检查 null,如果 null 使用 0 作为 itemCount 否则使用它的长度。

关于flutter - Flutter StatefulWidget 中的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56795355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com