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

Flutter从Firebase获取Map数组结合ModelClass解析报错解决

问题描述

我需要为SalonModel类中嵌套的服务模型匹配对应Firebase文档结构完成建模。目前已可完成SalonModel全字段的建模,但尝试对SalonServices服务模型建模时始终无法正常运行。

Firebase文档结构截图:
Firebase salonServices字段结构

以下是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,

问题更新

无法完成数据映射,未找到可用的映射方法,相关调试截图如下:
调试截图1
调试截图2

最终解决方案

解决方案附在下方

报错核心原因是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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 03:54:24