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

Flutter中无法从Firebase Cloud Firestore获取数据存入列表

问题原因与解决方案

你遇到的核心问题是:调用collection('interventions').get()返回的是QuerySnapshot类型对象,它没有data()方法——data()是用于单个文档的DocumentSnapshot对象的方法。QuerySnapshot代表集合的查询结果集合,需要通过docs属性获取所有文档快照列表。

修正后的代码

基础遍历写法

Future<List<Intervention>> fetchInterventions() async {
  List<Intervention> ivs = [];
  final querySnapshot = await FirebaseFirestore.instance.collection('interventions').get();
  // 遍历查询结果中的每一个文档快照
  for (var docSnapshot in querySnapshot.docs) {
    // 调用单文档快照的data()获取字段映射
    ivs.add(Intervention.fromJson(docSnapshot.data()));
  }
  return ivs;
}

简洁的map写法

Future<List<Intervention>> fetchInterventions() async {
  final querySnapshot = await FirebaseFirestore.instance.collection('interventions').get();
  // 直接将文档快照列表转换为Intervention列表
  return querySnapshot.docs
      .map((docSnapshot) => Intervention.fromJson(docSnapshot.data()))
      .toList();
}

额外注意事项

  • 确保Firestore文档中的字段名和你fromJson方法里使用的key完全一致(比如date_iv、numIntervention),拼写错误会导致对象初始化失败。
  • 如果Firestore中存在字段缺失的情况,建议在fromJson中添加空值兜底,例如:
    static Intervention fromJson(Map<String, dynamic> map) {
      return Intervention(
          dateIv: map['date_iv'] ?? '',
          etat: map['etat'] ?? '',
          intervention: map['intervention'] ?? '',
          numero: map['numIntervention'] ?? '',
          prix: map['prix'] ?? 0);
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:40:23