首页 > 解决方案 > Flutter:获取文档快照

问题描述

我创建了一个 Listview 构建器buildChatList作为我的 itembuilder 传递,但我注意到buildChatList当我热重启或重建应用程序时没有返回任何内容,但当我热重载时实际上返回了预期的数据。我不明白为什么会这样。我需要帮助。

以下是我到目前为止的代码。

buildChatList(BuildContext context, int index) {
    Map<String, dynamic> userDocumentt;
    print('INDEX $index COUNT $currentUserActiveChatsLength');
    String thisUserID = currentUserActiveChats[index];
    if (user.uid.hashCode <= thisUserID.hashCode) {
      groupChatId = '$_cuserID-$thisUserID';
    } else {
      groupChatId = '$thisUserID-$_cuserID';
    }
    Stream<QuerySnapshot> unreadMessages = Firestore.instance
        .collection('messages')
        .where("chatDetails.to", isEqualTo: user.uid)
        .where("chatDetails.sender", isEqualTo: thisUserID)
        .where("chatDetails.hasRead", isEqualTo: false)
        .snapshots();
    unreadMessages.listen((QuerySnapshot data) {
      unReadMessageLength = data.documents.length;
    });

    Stream<QuerySnapshot> lastMess = Firestore.instance
        .collection('messages')
        .where('groupChatId', isEqualTo: groupChatId)
        .orderBy('chatDetails.timestamp', descending: true)
        .limit(1)
        .snapshots();
    lastMess.listen((QuerySnapshot data) {
      List<DocumentSnapshot> userLastMess = data.documents;
      chatDetailSnapshotList = userLastMess.map((DocumentSnapshot doc) {
        return doc.data;
      }).toList();
    });
    Stream<DocumentSnapshot> userP = usersRef.document(thisUserID).snapshots();
    userP.listen((DocumentSnapshot snap) {
      userDocumentt = Map.from(snap.data);
      if (userDocumentt != null) {
        print('HELLOo $userDocumentt');
        myResult = new InkWell(
          highlightColor: Colors.grey[300],
          onTap: () {
            Navigator.of(context, rootNavigator: true).push(
                new MaterialPageRoute(
                    builder: (context) =>
                        new Chat(chatWith: userDocumentt['id'])));
          },
          onLongPress: () {
            setState(() {
              modifyMode = true;
            });
          },
          child: new Container(
            margin: EdgeInsets.only(left: 15.0, right: 15.0),
            child: new Column(
              children: <Widget>[
                new Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[

                    new Expanded(
                      child: new Container(
                        child: new Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            new Container(
                              margin: EdgeInsets.only(left: 17.0, top: 5.0),
                              child: new Text(
                                userDocumentt['username'],
                                style: new TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16.0,
                                ),
                              ),
                            ),
                            new Container(
                              margin: EdgeInsets.only(left: 17.0, top: 7.0),
                              child: new Text(
                                chatDetailSnapshotList[0]["chatDetails"]
                                    ["content"],
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: new TextStyle(
                                  fontSize: 15.0,
                                  color: Colors.grey[800],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                new Container(
                  margin: EdgeInsets.only(left: 72.0, top: 6.0, bottom: 6.0),
                  child: new Divider(
                    color: Colors.grey[300],
                    height: 10.0,
                  ),
                ),
              ],
            ),
          ),
        );
      } else {
        print('HELLLLOOO $userDocumentt');
        myResult = CircularProgressIndicator();
      }
    });
    return myResult;
  }

标签: dartnosqlfluttergoogle-cloud-firestore

解决方案


对于 Firestore 使用“StreamBuilder”进行实时更新是有意义的,我给你一个我拥有的示例代码,希望它有帮助。

StreamBuilder(
                 stream: Firestore.instance.collection("YourCollectionNAme").snapshots(),
                 builder: (BuildContext  context,AsyncSnapshot snapshot)
                 {
                   if (snapshot.hasData)
                   {
                   return new ListView.builder(
                     shrinkWrap: true,
                     itemCount: snapshot.data.documents.length,
                     padding: const EdgeInsets.only(top: 5.0),
                     itemBuilder: (context, index) {
                      DocumentSnapshot ds = snapshot.data.documents[index];
                      return new Row(
                        textDirection: TextDirection.ltr,
                          children: <Widget>[
                            Expanded (child:Text(ds["Field-of-collection"]) ),
                            Expanded (child:Text(ds["another-field"]) ),
                            Expanded (child:Text(ds["last-field"].toString()) ),


                          ],
                      );
      }
                   );
                 }
                 },
               )

我正在为我的 Firestore 集合使用列表视图。


推荐阅读