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

如何使用Dart cloud_firestore包获取Cloud Firestore未知文档名称列表

问题分析与解决方案

你的代码返回空列表的核心原因是:response.docs.map(...)仅生成了包含Customer对象的可迭代对象,但没有将这些对象添加到customers列表中,也没有将转换后的结果赋值给列表。

修复方案一:使用forEach直接添加元素

将map替换为forEach,在循环内部把创建好的Customer对象添加到列表:

class Customer {
  Customer({
    required this.document,
    required this.customer,
  });
  final String document;
  final Map<String,dynamic> customer;
}

Future<List<Customer>> getAllCustomersFromDatabase()async{
  List<Customer> customers = [];
  FirebaseFirestore db = FirebaseFirestore.instance;
  QuerySnapshot<Map<String, dynamic>> response = await db.collection(customersCollection).get();
  
  response.docs.forEach((doc){
    String docName = doc.id;
    Map<String, dynamic> document = doc.data();
    Customer customer = Customer(
      document: docName,
      customer: document,
    );
    customers.add(customer); // 关键:将对象添加到列表
    print(customer.document);
    print(customer.customer);
  });
  
  return customers;
}

修复方案二:利用map转换后转为List

直接将map返回的可迭代对象通过toList()转为列表并赋值:

class Customer {
  Customer({
    required this.document,
    required this.customer,
  });
  final String document;
  final Map<String,dynamic> customer;
}

Future<List<Customer>> getAllCustomersFromDatabase()async{
  FirebaseFirestore db = FirebaseFirestore.instance;
  QuerySnapshot<Map<String, dynamic>> response = await db.collection(customersCollection).get();
  
  List<Customer> customers = response.docs.map((doc){
    String docName = doc.id;
    Map<String, dynamic> document = doc.data();
    return Customer(
      document: docName,
      customer: document,
    );
  }).toList(); // 关键:调用toList()生成列表
  
  return customers;
}

补充说明

  • 原有的getAllServicesFromDatabase函数是针对单个文档内的字段进行读取,而新需求是读取集合下所有文档的ID和数据,两者的核心区别在于前者用doc().get()获取单文档快照,后者用collection().get()获取查询快照(包含多个文档)。
  • 两种修复方案都能正确获取集合内所有文档的名称(doc.id)和对应数据(doc.data()),并封装为Customer对象列表返回。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:23:16