我们如何需要使用快照和Futurebuilder?

时间:2020-04-23 21:05:00

标签: flutter

就目前而言,当我使用futurebuilder和快照时,我会这样: 所以将来我会用数据设置功能。经过测试后,我等待快照。您如何看待这种工作方式,我不确定这是正确的

FutureBuilder(
              future: ListLotto,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting:
                    return new Center(
                      child: new CircularProgressIndicator(),);
                  default:
                    if (snapshot.hasError) {
                      return new Center(
                        child: new Text('Error: ${snapshot.error}'),);
                    }
                    else {
                        List<Lotto_grid> values = snapshot.data;
                        if (values.isEmpty) {
                        return Container(

1 个答案:

答案 0 :(得分:0)

   FutureBuilder(
          future: myFuture,
          initialData: initialValue,//specify it if necessary
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            switch(snapshot.connectionState){
              case ConnectionState.done:
                if(snapshot.hasError) {
                  return myErrorWidget();
                } else if(snapshot.hasData) {
                  return MyDataWidget();
                } else{//if snapshot.data == null
                  return MyOtherWidget();
                }
              default:
                return CircularProgressIndicator();
            }
          }
      )

这是更好的选择,因为它检查数据是否为空,所以您在此行不会得到NullPointerException

列表值= snapshot.data;