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

Flutter中从Firestore子集合获取文档失败的问题排查

问题:Flutter从Firestore子集合获取文档ID返回“未找到文档”

我尝试通过Flutter代码从Firestore的Users集合下当前用户文档的Chats子集合中获取文档ID,但页面始终返回“未找到文档”。

Firestore数据结构

  • Users集合:文档以用户ID命名
  • 每个用户文档下包含Chats子集合
  • Chats中的文档以商品ID命名,每个文档下还有Messages子集合用于存储消息文档

Firestore数据截图

Firestore数据结构截图1
Firestore数据结构截图2

我的代码

return Scaffold(
  appBar: AppBar(
    title: const Text('Subcollection Documents'),
  ),
  body: FutureBuilder<QuerySnapshot>(
    future: FirebaseFirestore.instance
        .collection('Users')
        .doc(user!.uid)
        .collection('Chats')
        .get(),
    builder: (context, snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      } else if (snapshot.hasError) {
        return Center(
          child: Text('Error: ${snapshot.error}'),
        );
      } else if (snapshot.hasData) {
        final documents = snapshot.data!.docs;
        return ListView.builder(
          shrinkWrap: true,
          primary: true,
          itemCount: documents.length,
          itemBuilder: (context, index) {
            final docId = documents[index].id;
            return ListTile(
              title: Text(docId),
            );
          },
        );
      } else {
        return const Center(
          child: Text('No documents found.'),
        );
      }
    },
  ),
);
解决方法
  • 检查集合/文档名称大小写
    Firestore对集合、文档名称大小写敏感,确保代码中的Users、Chats和后台完全一致,比如后台是users就不能写成Users。

  • 验证用户ID正确性
    打印user!.uid的值,对比Firestore中Users集合下的目标文档ID,确认当前用户的UID和目标文档ID匹配。

  • 排查Firestore安全规则
    如果安全规则限制了读取权限,即使文档存在也无法获取。开发环境可临时使用测试规则(测试后需改回严格规则):

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if request.auth != null;
        }
      }
    }
    
  • 确认子集合文档存在
    检查当前用户的Chats子集合下是否确实有文档,避免文档被误创建到其他用户的子集合中。

  • 确保用户对象已初始化
    进入页面之前确认用户已登录,避免user为null导致的错误(虽然代码用了user!,但提前校验能排除隐患)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:25:28