Flutter StatefulWidget的可变范围

时间:2019-06-27 16:34:32

标签: flutter statefulwidget

我正在尝试访问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();
          },
        ));
  }
}

2 个答案:

答案 0 :(得分:1)

使用

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

您的build()moviesList初始化之前被调用,因此如果null使用null作为{{1},则在这里我们首先检查0 } else使用它的长度。

答案 1 :(得分:0)

解决方案(可能是一种):

该问题背后的真正原因不是可变范围,而是异步的方式完全错误,重新设计解决了该问题。已将_getLatestMovies();移动到FutureBuilder中。

改进了以下内容之一:

  @override
  Widget build(context) {
    var futureBuilder = FutureBuilder(
        future: _getLatestMovies(),
        builder: (context, snapshot) {
          if (snapshot.data != null) {
            return ListView.separated(
                padding: EdgeInsets.zero,

通过此移动,FutureBuilder等待方法的结果,并作为快照传递到ListView。