Flutter:获取文档快照

时间:2018-10-17 23:40:43

标签: dart nosql flutter google-cloud-firestore

我创建了一个通过buildChatList作为我的itembuilder的Listview构建器,但是我发现当我热重启或重建应用时,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;
  }

3 个答案:

答案 0 :(得分:1)

对于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集合。

答案 1 :(得分:0)

您将需要使用StreamBuilder而不是普通的ListView.builder()。 检查此link

更新数据并不意味着更新视图,您需要在添加的每个新记录上重建此小部件,因此当您热重新加载应用程序时,您将手动运行setState()以便显示更新。

StreamBuilder将在每个新记录上为您执行setState()

答案 2 :(得分:0)

我想你不是要返回流吗?

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();
});
myResult = Stream<DocumentSnapshot> userP = usersRef.document(thisUserID).snapshots();
userP.listen((DocumentSnapshot snap) {
  userDocumentt = Map.from(snap.data);
  if (userDocumentt != null) {
    print('HELLOo $userDocumentt');
    return 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;

}