如何在Flutter中的Firebase快照上调用Future?

时间:2018-05-12 21:40:21

标签: asynchronous stream async-await dart flutter

当我使用StreamBuilder返回快照时,我得到的重复错误仅持续一两秒钟,该快照调用“在null上调用快照”。我相信我需要让我的快照异步,但我可能完全错了。这是我的代码......

child: new StreamBuilder(
                        stream: fb.child('UserVideo/${fUser.uid}').orderByKey().onValue,
                        builder: (BuildContext context, AsyncSnapshot<Event> event) {
                          if (event.data.snapshot.value == null) {
                            return new Card(
                              child: new Center(
                                child: new Text('SEARCH',
                                    textAlign: TextAlign.center,
                                    style: new TextStyle(
                                        fontSize: 30.0,
                                        fontFamily: 'Chewy',
                                        color: Colors.black)),
                              ),
                            );
                          } else if (event.data.snapshot.value != null) {
                              Map unsorted =
                                  event.data.snapshot.value; //store each map

                              final myMap =
                              new SplayTreeMap<String, dynamic>.from(
                                  unsorted,
                                      (a, b) => unsorted[a]['rank']
                                      .compareTo(unsorted[b]['rank']));

                              //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();

                              for (var items in titles) {
                                onesTitles.add(items['title']);
                                onesIds.add(items['videoID']);
                                onesImages.add(items['imageString']);
                                onesRank.add(items['rank'].toString());
                              }

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

我正在将用户信息安排到列表中,然后从中填充卡片信息。

1 个答案:

答案 0 :(得分:2)

使用安全导航操作符可以防止该错误

event.data?.snapshot?.value

只有在评估为!= null

之前的部分时才会影响后续部分