首页 > 解决方案 > 在 Flutter Firebase 中,getter 'documents' 被调用为 null

问题描述

当我单击聊天选项卡时。它显示红屏错误几秒钟。然后它成功检索数据。当我点击错误。它把我带到了第二个streambuilder。

I/flutter (17397):在 null 上调用了 getter 'documents'。

我/颤振(17397):接收器:空

I/flutter (17397):尝试调用:文档

Widget chatRoomsList(){
    return StreamBuilder(
        stream: chatRooms,
        builder: (context, snapshot) {
          return snapshot.hasData ? ListView.builder(
              itemCount: snapshot.data.documents.length,
              shrinkWrap: true,
              itemBuilder: (context, index) {

                return StreamBuilder(
                    stream: Firestore.instance.collection("chatRoom").document(snapshot.data.documents[index].data["chatRoomId"]).collection("Chats").orderBy("time",descending: true).limit(1).snapshots(),
                    builder: (context, snapshot1) {
                      return snapshot.hasData ? ListView.builder(
                          itemCount: snapshot1.data.documents.length,
                          shrinkWrap: true,
                          itemBuilder: (context, index1) {
                            return  ChatRoomsTile(
                              userName:snapshot.data.documents[index].data['chatRoomId'].toString().replaceAll("_", "").replaceAll(Constants.myName, ""),
                              chatRoomId: snapshot.data.documents[index].data["chatRoomId"].toString(),
                              message: snapshot1.data.documents[index1]["message"].toString(),
                              Time:snapshot1.data.documents[index1]["time"],
                            );
                          }):Container();

                    });
              }):Container();
        });

  }

标签: firebasefluttergoogle-cloud-firestore

解决方案


问题就在StreamBuilder你拥有的那一秒之内。

在那里的构建器中,您正在检查是否snapshot有数据:

snapshot.hasData

您实际上应该检查是否snapshot1有数据:

snapshot1.hasData

因此,由于条件始终返回 true(当时snapshot的数据也是如此),但实际使用的数据是 from snapshot1,它会显示一个错误,直到它实际snapshot1从流中获取一些数据。


推荐阅读