导航到另一个页面时,在 null 上调用了 getter 'length'

时间:2020-12-24 13:23:49

标签: flutter dart

我收到错误快照数据长度为空来处理这个我添加了条件但是当我尝试导航到另一个页面时仍然显示错误这是我的代码

Scaffold(
  key: _scaffoldKey,
  drawer: new Drawer(
    child: ListView(
      padding: EdgeInsets.zero,
      children: [
        
  appBar: new AppBar(
    backgroundColor: Colors.white,
    elevation: 1,
    title: new Text("FindTheRecipe"),
    actions: [
      new IconButton(
          icon: Icon(Icons.search),
          onPressed: () async {
            Navigator.push(
                context, MaterialPageRoute(builder: (context) => sample()));
           
          })
    ],
  ),

下一页

import 'package:flutter/material.dart';
import 'package:find_recipe/responses.dart';

class sample extends StatefulWidget {
@override
_sampleState createState() => _sampleState();
}

class _sampleState extends State<sample> {
Future _future;
@override
void initState() {
_future = mylist();
super.initState();
 }

@override
Widget build(BuildContext context) {
 return Scaffold(
  appBar: new AppBar(),
  body: FutureBuilder(
    future: _future,
    builder: (context, snashot) {
      return ListView.builder(
        itemCount: snashot.data.length,
        itemBuilder: (BuildContext context, int index) {
          if (snashot.data.length == null) {
            return CircularProgressIndicator();
          } else {
            return Text("asdasd");
          }
        },
      );
     },
   ),
 );
}
}

我添加了条件,但为什么显示错误,请帮助我。它显示错误而不是 CircularProgressIndicator()

1 个答案:

答案 0 :(得分:1)

异步快照需要时间来加载。它们具有 .hasData 和 .hasError 等属性,可以检查它们以返回适当的小部件。 snapshot.data 为空,直到 snapshot.hasData 为真,这意味着数据仍在加载。所以基本上,当snapshot.data 为空时,您正在调用snapshot.data.length 导致错误。

要修复它,请在使用快照前检查以下两点:

if(!snapshot.hasData) { return LoadingWidget(); } // Loading widget is a widget you want to show while the data is being loaded. For example, a CircularProgressIndicator
if(snapshot.hasError) { return ErrorWidget(); } // Error widget can be anything you want to show if an error occurs while loading the data. You can return something like Text("Error");

然后返回正常的东西

return ListView.builder(....); // Rest of the code