首页 > 解决方案 > 如何从firestore获取嵌套集合数据

问题描述

我有一个如下所示的 Firestore 集合。我需要获取最后存储的message.

Firestore-root
  |
  --- chat_rooms(collection)
        |
        --- chats(collection, the id for that collection is sender_reciever)
             |
             --- time_send: (millisecondsSinceEpoch)
             |
             --- sender:(string)
             |
             --- message:(string)



这是我db获取最后一个消息的方法

  getLastMessage(String chatRoomId) {
    return  Firestore.instance.
    collection('chat_rooms').document(chatRoomId)
        .collection('chat').orderBy('time_send',descending: false)
        .limit(1).get();
  }

我在这里称呼它。Chats是一个返回senderand的小部件last_message。基本上我想做的是,例如,在使用whatsapp时,最后一条消息会弹出主页。我正在尝试做完全相同的事情。这样,我也可以得到username。下面的方法不返回实际的用户数据。由于该集合chat_rooms_id的 id 是username_sender和的组合username_reciever。我只是删除了reciever当前用户。还有,sender剩下的。

   return Chats(
                      username: snapshot.data.documents[index]
                          .data["chat_room_id"] // return chat_room id
                          .toString()
                          .replaceAll("_", "")
                          .replaceAll(Constants.signedUserName, ""),
                      chatRoomId:
                          snapshot.data.documents[index].data["chat_room_id"],
                      last_message: __db
                          .getLastMessage(snapshot
                              .data.documents[index].data[snapshot.data.documents[index]
                                  .data['chat_room_id'].toString()]
                              .toString()).toString()
                    );

结果是 结果

标签: flutterdartgoogle-cloud-firestore

解决方案


首先,创建一个类来存储聊天信息

class Chat {
  final String id;
  final time_send;
  final String sender;
  final String message;
  
  Chat({this.id, this.time_send, this.sender, this.message});
  
  
  static Chat fromSnapshot(QuerySnapshot snap) {
    return Chat(
      id: snap.id,
      time_send: snap.get('time_send'),
      sender: snap.get('sender'),
      message: snap.get('message'),
    );
  }
}

然后,如下修改您的 Firestore 查询,使用 snapshots() 而不是 get() 方法

Stream<Chat> chat(String chatRoomId) {
  return  Firestore.instance.
    collection('chat_rooms').document(chatRoomId)
    .collection('chat').orderBy('time_send',descending: false)
    .limit(1)
    .snapshots()
    .map<Chat>((snapshot) {
       if (snapshot.size > 0) {
          return snapshot.docs.map((e) => Chat.fromSnapshot(e)).single;
       } 
 });

推荐阅读