flutter - 如何从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
是一个返回sender
and的小部件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()
);
解决方案
首先,创建一个类来存储聊天信息
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;
}
});
推荐阅读
- php - 如何获取并存储我单击按钮所在行的 ID?
- python - 替换python中具有动态字符的字符串
- apache-nifi - 如何从 Nifi 中的 xml 中提取值(列表和唯一标签)?
- sql - 动态 SQL:为具有关系的表创建插入查询
- python - python_slicing 我在某些示例中看到我们使用两个括号,但在其他示例中我们使用两个我有点困惑所以我该如何使用它们
- java - 加入一组具有整体超时的线程
- c++ - 如何在不复制 C++ 的情况下分配嵌套的 protobuf?
- python - 我将如何跟踪大量 grequest 的进度?
- xcode - 如何在此 Google Apss 脚本中插入图表?
- c# - 调试使用事件网格触发的 Azure 函数