[英]Flutter Firestore how to convert document content to stream
我在 Firestore 中有一個文檔,其中包含一張聊天消息圖:
'a': { 'sentAt': '...', 'content': '...' },
'b': { 'sentAt': '...', 'content': '...' },
'c': { 'sentAt': '...', 'content': '...' },
我想創建一個Firestore 服務來偵聽該文檔中的更改(例如添加的新消息)並返回消息流(Map<String, MessageModel>),如下所示:
Stream<Map<String, MessageModel>> getMessagesStream() {
return _firestore
.collection('chats')
.doc('chat')
.snapshots()
.map((snapshot) =>
???
);
}
我怎樣才能做到這一點(那里應該安裝什么??? )?
這不起作用:
(snapshot.data() as Map)
.cast<String, dynamic>()
.forEach((key, value) {
key: MessageModel.fromJson(value);
})
編輯:似乎這樣可以完成工作:
Stream<Map<String, MessageModel>> getMessagesStream() {
return _firestore
.collection('chats')
.doc('chat')
.snapshots()
.asyncMap((snapshot) => {
for (var message in (snapshot.data() as Map).entries)
message.key:
MessageModel.fromJson(message.value)
});
}
仍然不確定 .map 和 .asyncMap 之間有什么區別......
也很想聽聽您對這種方法的看法(Firestore 即服務等)
你要找的是 asyncMap
https://api.flutter.dev/flutter/dart-async/Stream/asyncMap.html
Stream<Map<String, MessageModel>> getMessagesStream() {
return _firestore
.collection('chats')
.doc('chat')
.snapshots()
.asyncMap((snapshot) =>
// Convert your snapshot to Map<String, MessageModel>
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.