在显示之前,根据从StreamBuilder获得的数据执行异步操作

时间:2019-01-12 23:21:34

标签: dart flutter google-cloud-firestore

我目前正在使用StreamBuilder从Firestore获取数据,到目前为止,它运行良好。

我当前要在显示之前对数据执行一些async操作。

获取数据的代码如下。

    List<Model> listToDisplay = new List<Model>();

      @override
      Widget build(BuildContext context) {    
    return DefaultTabController(
    length: 2,
    child: Scaffold(
        appBar: topBar,
        body: StreamBuilder(
            stream: Firestore.instance.collection('/myPath').snapshots(),
            builder: (BuildContext context,
                AsyncSnapshot<QuerySnapshot> snapshot) {
              if(snapshot.connectionState == ConnectionState.active) {
                listToDisplay.clear();
                for (DocumentSnapshot _snap in snapshot.data.documents) {
                  Model _add = new Model.from(_snap);
                  listToDisplay.add(_add);
                }
                return TabBarView(
                  children: <Widget>[
                    ListView.builder(
                      itemCount: mouveList.length,
                      itemBuilder: (context, index) {
                        return Card(listToDisplay[index]);
                      },
                    ),
                    Icon(Icons.directions_transit),
                  ],
                );
              } else {
                return Container(
                    child: Center(child: CircularProgressIndicator()));
              }
            })));

我尝试在for in循环中添加异步操作,但这没有用,它没有等待它。另外,添加await无效,因为Widget build(BuildContext context)无法异步。

      @override
      Widget build(BuildContext context) {    
    return DefaultTabController(
    length: 2,
    child: Scaffold(
        appBar: topBar,
        body: StreamBuilder(
            stream: Firestore.instance.collection('/myPath').snapshots(),
            builder: (BuildContext context,
                AsyncSnapshot<QuerySnapshot> snapshot) {
              if(snapshot.connectionState == ConnectionState.active) {
                listToDisplay.clear();
                for (DocumentSnapshot _snap in snapshot.data.documents) {
                  Model _add = new Model.from(_snap);
                  //Added
                  //_add.getCalculate(); <------- Async function
                  _add.Calculate(); <------ Flutter does not wait for this
                 await _add.Calculate(); <------ Produces an error

                 listToDisplay.add(_add);
                }
                return TabBarView(
                  children: <Widget>[
                    ListView.builder(
                      itemCount: mouveList.length,
                      itemBuilder: (context, index) {
                        return Card(listToDisplay[index]);
                      },
                    ),
                    Icon(Icons.directions_transit),
                  ],
                );
              } else {
                return Container(
                    child: Center(child: CircularProgressIndicator()));
              }
            })));

关于如何使用流StreamBuilderListViewBuilder显示数据之前如何获取数据,对数据执行操作的任何想法?

1 个答案:

答案 0 :(得分:0)

我目前正在迭代StreamBuilder中相应列表中的数据,然后使用ListView.builder显示List.count中的每个数据项。代码以这些公共/文件列表开头...

List names = new List();
List ids = new List();
List vidImages = new List();
List numbers = new List();

然后在我的有状态窗口小部件生成器中...

child: new StreamBuilder(
                      stream:
                          fb.child('child').orderByChild('value').onValue,
                      builder:
                          (BuildContext context, AsyncSnapshot<Event> event) {
                        if (event.data?.snapshot?.value == null) {
                          return new Card(
                            child: new Text(
                                'Network Error, Please Try again...',
                                style: new TextStyle(
                                    fontSize: 12.0,
                                    fontWeight: FontWeight.bold,
                                    fontStyle: FontStyle.italic)),
                          );
                        } else if (event.data?.snapshot?.value != null) {
                          Map myMap =
                              event.data?.snapshot?.value; //store each map

                          var titles = myMap.values;

                          List onesTitles = new List();
                          List onesIds = new List();
                          List onesImages = new List();
                          List onesRank = new List();

                          List<Top> videos = new List();

                          for (var items in titles) {
                            var top = new Top(
                                videoId: items['vidId'],
                                rank: items['Value'],
                                title: items['vidTitle'],
                                imageString: items['vidImage']);
                            videos.add(top);
                            videos..sort((a, b) => b.rank.compareTo(a.rank));
                          }

                          for (var vids in videos) {
                            onesTitles.add(vids.title);
                            onesIds.add(vids.videoId);
                            onesImages.add(vids.imageString);
                            onesRank.add(vids.rank);
                          }

                          names = onesTitles;
                          ids = onesIds;
                          numbers = onesRank;
                          vidImages = onesImages;

                          switch (event.connectionState) {
                            case ConnectionState.waiting:
                              return new Card(
                                child: new Text('Loading...',
                                    style: new TextStyle(
                                        fontSize: 12.0,
                                        fontWeight: FontWeight.bold,
                                        fontStyle: FontStyle.italic)),
                              );
                              else
                                return new InkWell( child: new ListView.builder(
                                      itemCount:
                                          names == null ? 0 : names.length,
                                      itemBuilder:
                                          (BuildContext context, int index) {
                                        return new Card( child: new Text(names[index]))