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

如何通过FlutterFire在FireStore中批量按ID查询文档?

FlutterFire FireStore批量获取指定ID文档的方案

你可以使用FireStore提供的getAll()方法来批量获取多个指定ID的文档,无需逐个请求或添加冗余字段,具体实现如下:

  1. 创建文档引用列表
    先为每个目标文档ID生成对应的DocumentReference:

    final List<DocumentReference> docRefs = [
      FirebaseFirestore.instance.collection('groups').doc(id1),
      FirebaseFirestore.instance.collection('groups').doc(id2),
      FirebaseFirestore.instance.collection('groups').doc(id3),
      FirebaseFirestore.instance.collection('groups').doc(id4),
    ];
    
  2. 批量获取文档
    调用getAll()方法传入文档引用列表,发起批量查询:

    final List<DocumentSnapshot> snapshots = await FirebaseFirestore.instance.getAll(docRefs);
    
  3. 处理查询结果
    遍历返回的DocumentSnapshot列表,处理每个文档的数据:

    for (final doc in snapshots) {
      if (doc.exists) {
        // 文档存在,获取数据和ID
        final docId = doc.id;
        final docData = doc.data();
        // 这里添加你的业务逻辑
      } else {
        // 处理文档不存在的情况
        print('文档 ${doc.id} 不存在');
      }
    }
    

注意事项

  • getAll()方法一次最多支持获取50个文档,如果你的ID列表超过50个,需要将列表分批处理,分多次调用该方法。
  • 该方法会将多个请求合并为一次网络请求,性能远优于逐个请求文档。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:40:54