Flutter 如何从firestore获取嵌套集合数据
我有一个firestore收藏,如下所示。我需要获取上次存储的Flutter 如何从firestore获取嵌套集合数据,flutter,dart,google-cloud-firestore,Flutter,Dart,Google Cloud Firestore,我有一个firestore收藏,如下所示。我需要获取上次存储的消息 Firestore-root | --- chat_rooms(collection) | --- chats(collection, the id for that collection is sender_reciever) | --- time_send: (millisecondsSinceEpoch)
消息
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
和last\u消息
。基本上,我想做的是,例如,在使用whatsapp时,最后一条消息会在主页上弹出。我想做完全相同的事情。这样,我也可以获得用户名。下面的方法不返回实际的用户数据。因为集合聊天室\u id
具有一个由用户名\u发送者
和用户名\u接收者
组合而成的id。我只是删除了当前用户的接收者
。而发送者
仍然存在
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()方法
流式聊天(字符串聊天室ID){
返回Firestore.instance。
集合(“聊天室”)。文档(聊天室ID)
.collection('chat').orderBy('time_send',降序:false)
.限额(1)
.快照()
.map((快照){
如果(snapshot.size>0){
返回snapshot.docs.map((e)=>Chat.fromsapshot(e)).single;
}
});
我在聊天类中遇到了一些错误,例如fromSnapshot()方法未定义id、发件人、使用的时间、消息等。此外,在查询方法中,还存在一些问题,单个
未定义。我的firestore版本为'cloud\u firestore:^0.13.0+1',我修改了方法,如返回snapshot.documents.map((e)=>Chat.fromSnapshot(e)).single
现在它说DocumentSnapshot不能分配给e
的查询snapshot
在聊天类中将fromSnapshot(QuerySnapshot snap)方法更改为fromSnapshot(DocumentSnapshot snap)方法。在这里,您还可以包含Chats()的定义吗
以及运行return chats()
的方法是如何定义的?根据future
的消息实例,似乎缺少一些async/wait
或then
关键字。上述是[1].[1]中描述的预期行为
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;
}
});