我尝试访问moviesList
中的build()
并得到如下结果。如果有人能指出真正的问题是。事先谢谢。
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/