You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中获取Firestore聊天室用户列表返回空,求解决方法

Flutter聊天应用无法获取Firestore房间用户列表的解决方法

问题背景

我开发了一个Flutter聊天应用,Firestore数据结构如下:
chats(集合)> roomId(随机生成ID的文档)> users(集合)> email(用户邮箱作为ID的文档)> messages(集合)> messageId(随机生成ID的文档)> 聊天内容

获取特定用户消息的代码可以正常运行,但获取房间内所有用户列表时返回空列表。

正常运行的代码

获取某房间内特定用户的所有消息:

FirebaseFirestore.instance
        .collection('chats')
        .doc(roomId)
        .collection('users')
        .doc(user)
        .collection('messages')
        .orderBy('timestamp', descending: true)
        .snapshots(),

异常代码(返回空列表)

获取房间内所有用户列表的代码:

QuerySnapshot<Map<String, dynamic>> userCollection = await FirebaseFirestore.instance
          .collection('chats')
          .doc(roomId)
          .collection('users')
          .get();

当前Firestore规则

规则设置为完全开放,排除权限问题:

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

问题根源与修正后的代码

检查发送消息的代码后发现,写入用户文档时存在拼写错误:widget.rooomId(多了一个字母o),导致用户数据被写入了错误的房间路径下,自然无法在正确的roomId下读取到用户列表。

修正拼写错误后的发送消息代码(已验证可正常运行):

await FirebaseFirestore.instance.collection('chats').doc(widget.roomId).set({
      'createdAt': FieldValue.serverTimestamp(),
    }, SetOptions(merge: true));

    await FirebaseFirestore.instance
        .collection('chats')
        .doc(widget.roomId) // 修正拼写错误:rooomId → roomId
        .collection('users')
        .doc(widget.user)
        .set({
      'joinedAt': FieldValue.serverTimestamp(),
    }, SetOptions(merge: true));

    await FirebaseFirestore.instance
        .collection('chats')
        .doc(widget.roomId)
        .collection('users')
        .doc(widget.user)
        .collection('messages')
        .add({
      'senderId': widget.user,
      'text': _messageController.text,
      'timestamp': FieldValue.serverTimestamp(),
      'isAdmin': widget.isAdmin
    });

修正后,用户文档会被正确写入目标房间的users集合,此时执行获取用户列表的代码即可正常返回所有用户数据。

内容的提问来源于stack exchange,提问作者Rohith Poyyeri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 11:12:36