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

Firestore读取指定子集合数据时出现重复值问题求助

Firestore子集合数据重复问题

数据结构

Collection>Document>Sub-Collection>Document:Users>Shaiyan>Statuses>05 Feb 2022 - 03 Mar 2022(示例文档)

问题现象

读取所有用户的Statuses子集合数据时,返回列表正常;但指定读取Shaiyan文档下的Statuses子集合数据时,返回列表出现重复值。


读取所有数据的代码

Future getDocIDs() async {
  await FirebaseFirestore.instance
      .collection('Users')
      //.orderBy('rank', descending: false)
      .get()
      .then((snapshot) => {
            snapshot.docs.forEach((document) {
              //print(document.reference);
              //documentIDs.add(document.reference.id);
              db
                  .collection('Users')
                  .doc(document.reference.id)
                  .collection("Statuses")
                  .get()
                  .then((value) {
                value.docs.forEach((element) {
                  //print(element.data());
                  documentIDs.add(element.data().toString());
                });
              });
            })
          });
  print(documentIDs);
  print(documentIDs.length);
  setState(() {});
}

读取指定Shaiyan数据的代码

Future getDocIDs() async {
  await FirebaseFirestore.instance
      .collection('Users')
      //.orderBy('rank', descending: false)
      .get()
      .then((snapshot) => {
            snapshot.docs.forEach((document) {
              //print(document.reference);
              //documentIDs.add(document.reference.id);
              db
                  .collection('Users')
                  .doc('Shaiyan')
                  .collection("Statuses")
                  .get()
                  .then((value) {
                value.docs.forEach((element) {
                  //print(element.data());
                  documentIDs.add(element.data().toString());
                });
              });
            })
          });
  print(documentIDs);
  print(documentIDs.length);
  setState(() {});
}

函数调用代码

Padding(
  padding: const EdgeInsets.symmetric(horizontal: 25.0),
  child: GestureDetector(
    onTap: getDocIDs,
    child: Container(
      padding: const EdgeInsets.all(25),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Colors.deepPurple.shade400,
            Colors.deepPurple.shade700,
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        //color: Colors.deepPurple,
        borderRadius: BorderRadius.circular(12),
      ),
      child: const Center(
        child: Text(
          'Print subcollection',
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
            fontSize: 20,
          ),
        ),
      ),
    ),
  ),
),

问题原因

读取指定用户数据的代码存在逻辑错误:先获取Users集合下的所有文档,然后遍历每一个用户文档时,都重复请求一次Shaiyan的Statuses子集合。假设Users集合有N个文档,Shaiyan的Statuses数据就会被添加N次,最终导致列表出现重复值。

而读取所有数据的代码是遍历每个用户文档,读取对应用户的Statuses子集合,因此不会重复。

解决方案

无需遍历所有Users文档,直接定位到Shaiyan的Statuses子集合即可,同时建议每次调用前清空旧数据避免叠加:

优化后代码(简洁版)

Future getDocIDs() async {
  // 清空旧数据,防止多次点击叠加
  documentIDs.clear();
  
  await db
      .collection('Users')
      .doc('Shaiyan')
      .collection("Statuses")
      .get()
      .then((value) {
        value.docs.forEach((element) {
          documentIDs.add(element.data().toString());
        });
      });
  
  print(documentIDs);
  print(documentIDs.length);
  setState(() {});
}

更易读的await写法

Future getDocIDs() async {
  documentIDs.clear();
  
  final statusesSnapshot = await db
      .collection('Users')
      .doc('Shaiyan')
      .collection("Statuses")
      .get();
  
  for (final doc in statusesSnapshot.docs) {
    documentIDs.add(doc.data().toString());
  }
  
  print(documentIDs);
  print(documentIDs.length);
  setState(() {});
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:17:53