繁体   English   中英

Flutter Firestore 如何将文档内容转换为流

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM