Flutter从Firebase获取Map数组结合ModelClass解析报错解决
问题描述
我需要为SalonModel类中嵌套的服务模型匹配对应Firebase文档结构完成建模。目前已可完成SalonModel全字段的建模,但尝试对SalonServices服务模型建模时始终无法正常运行。
Firebase文档结构截图:
以下是SalonModel类的部分实现代码:
class SalonModel { String? uid; String? name; SalonServices? salonServices; SalonModel({this.uid, this.name, this.salonServices}) factory SalonModel.fromMap(Map<String, dynamic> map) { return SalonModel( uid: map['uid'], name: map['name'], salonServices: map['salonServices'] != null ? SalonServices.fromMap(map['salonServices']) : null, ); }
以下是SalonServices类的实现代码:
class SalonServices { String? serviceName; String? serviceDescription; bool? isActive; int? servicePrice; int? serviceDiscount; SalonServices({ this.serviceName, this.serviceDescription, this.isActive, this.servicePrice, this.serviceDiscount, }); Map<String, dynamic> toMap() { return { 'serviceName': serviceName, 'serviceDescription': serviceDescription, 'isActive': isActive, 'servicePrice': servicePrice, 'serviceDiscount': serviceDiscount, }; } factory SalonServices.fromMap(Map<String, dynamic> map) { return SalonServices( serviceName: map['serviceName'], serviceDescription: map['serviceDescription'], isActive: map['isActive'], servicePrice: map['servicePrice']?.toInt(), serviceDiscount: map['serviceDiscount']?.toInt(), ); } }
数据拉取与建模函数实现如下:
Future<SalonModel> fetchMyDatas(String uid) async { var doc = await FirebaseFirestore.instance.collection('salons').doc(uid).get(); Map<String, dynamic>? docData = doc.data(); return SalonModel.fromMap(docData!); }
运行函数时抛出如下异常:
Unhandled Exception: type 'List' is not a subtype of type 'Map<String, dynamic>'
定位异常位置可知,SalonModel.fromMap方法中如下代码行执行失败:
salonServices: map['salonServices'] != null ? SalonServices.fromMap(map['salonServices']) : null,
问题更新
无法完成数据映射,未找到可用的映射方法,相关调试截图如下:

最终解决方案
解决方案附在下方
报错核心原因是Firestore中salonServices字段存储的是服务对象数组,而非单个服务对象,原代码将其按单个Map对象解析才会触发类型不匹配错误,修复步骤如下:
- 修改SalonModel类中
salonServices字段的类型定义:
List<SalonServices>? salonServices;
- 调整SalonModel.fromMap方法中的解析逻辑,遍历数组逐个解析服务对象:
salonServices: json['salonServices'] == null ? null : List<SalonServices>.from( json['salonServices'].map((x) => SalonServices.fromMap(x)))
修改完成后fetchMyDatas函数可正常运行,数据解析成功。
内容的提问来源于stack exchange,提问作者Tolga Yılmaz
相关产品推荐
相关产品推荐

