Firestore文档Array字段转自定义对象列表问题求助
解决Firestore数组转List的问题
你的问题核心在于Colleague类的构造函数类型不匹配:你写的Colleague.fromMap接收的是DocumentSnapshot,但Firestore文档中LIST_OF_ALL_COLLEAGUES数组里的每个元素其实是Map<String, dynamic>(不是完整的DocumentSnapshot),直接用这个构造函数转换自然会失败。
下面是具体的修复步骤和代码:
1. 给Colleague类添加Map转实体的构造函数
保留原来的从DocumentSnapshot初始化的构造函数(如果需要从单个Colleague文档获取数据的话),新增一个专门处理普通Map的构造函数:
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:snagsnapper/Contants/constants.dart'; class Colleague { String name; String email; String phone; String uniqueID; Colleague({ this.name, this.email, this.phone, this.uniqueID, }); // 用于从单个Firestore文档获取数据(可选保留) Colleague.fromDocumentSnapshot(DocumentSnapshot data) : this( name: data[NAME], email: data[EMAIL], phone: data[PHONE], uniqueID: data[UID], ); // 新增:从Map<String, dynamic>转换为Colleague实体 Colleague.fromJson(Map<String, dynamic> map) : this( name: map[NAME], email: map[EMAIL], phone: map[PHONE], uniqueID: map[UID], ); Map<String, dynamic> toJSON() => { NAME : name, EMAIL : email, PHONE : phone, UID : uniqueID, }; }
2. 修改User类的fromMap方法
在转换listOfALLColleagues时,使用新增的fromJson构造函数遍历数组元素:
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:snagsnapper/Contants/constants.dart'; import 'package:snagsnapper/Data/colleague.dart'; class User { String name; String dateFormat='dd-MM-yyyy'; List<Colleague> listOfALLColleagues; User ({ this.name, this.dateFormat, this.listOfALLColleagues, }); User.fromMap(DocumentSnapshot data) : this( name: data[NAME], dateFormat: data[DATE_FORMAT], // 安全转换:先转成List<dynamic>,再逐个转成Colleague listOfALLColleagues: (data[LIST_OF_COLLEAGUES] as List<dynamic>) .map((colleagueMap) => Colleague.fromJson(colleagueMap as Map<String, dynamic>)) .toList(), ); Map<String, dynamic> toJSON() => { NAME : name, DATE_FORMAT : dateFormat, // 存回Firestore时,需要把Colleague转成Map数组 LIST_OF_COLLEAGUES : listOfALLColleagues?.map((colleague) => colleague.toJSON())?.toList(), }; }
额外注意点
- 类型转换时加上
as List<dynamic>和as Map<String, dynamic>是为了避免运行时类型错误,确保类型安全 - 存回Firestore时,
listOfALLColleagues必须转成List<Map>,所以要调用每个Colleague的toJSON()方法,否则Firestore无法正确存储这个数组
这样修改后,就能成功把Firestore中的LIST_OF_ALL_COLLEAGUES数组转换为List<Colleague>了。
内容的提问来源于stack exchange,提问作者Damandroid
相关产品推荐
相关产品推荐

