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

Flutter类型不匹配错误修复:_Map<String,dynamic>非String?子类型

修复Flutter中BvnConsent.fromJson类型转换错误方案

错误根源

该错误是因为BvnConsent模型的字段类型与接口返回数据的结构不匹配,同时存在冗余的JSON转换操作放大了类型冲突。具体来说:

  • 模型中某个字段被定义为String?,但接口返回的对应字段是Map<String, dynamic>类型
  • 多余的jsonDecode(jsonEncode(value.data))操作完全没必要,甚至会引入额外的类型风险

具体修复步骤

1. 移除冗余的JSON转换操作

根据你使用的网络库,直接传递正确格式的数据:

  • 如果用Dio:接口返回的value.data已经是解析完成的Map<String, dynamic>,直接传入fromJson:
    final response = BvnConsent.fromJson(value.data as Map<String, dynamic>);
    
  • 如果用http包:value.data是字符串,只需一次解析:
    final response = BvnConsent.fromJson(jsonDecode(value.data));
    

2. 对齐模型与接口返回的字段类型

假设你的接口返回数据结构如下(示例):

{
  "consent_id": "CT-12345",
  "customer_details": {
    "bvn": "12345678901",
    "full_name": "John Doe"
  },
  "status": "approved"
}

如果原来的BvnConsent模型把customer_details定义为String?,就会触发类型错误,需要修改模型:

class BvnConsent {
  final String? consentId;
  // 将String?改为嵌套模型或Map类型
  final CustomerDetails? customerDetails;
  final String? status;

  BvnConsent({this.consentId, this.customerDetails, this.status});

  factory BvnConsent.fromJson(Map<String, dynamic> json) {
    return BvnConsent(
      consentId: json['consent_id'],
      // 解析嵌套结构
      customerDetails: json['customer_details'] != null 
          ? CustomerDetails.fromJson(json['customer_details']) 
          : null,
      status: json['status'],
    );
  }
}

// 新增嵌套模型类
class CustomerDetails {
  final String? bvn;
  final String? fullName;

  CustomerDetails({this.bvn, this.fullName});

  factory CustomerDetails.fromJson(Map<String, dynamic> json) {
    return CustomerDetails(
      bvn: json['bvn'],
      fullName: json['full_name'],
    );
  }
}

3. 安全类型校验(可选)

如果接口返回字段类型不稳定,可以添加类型判断避免崩溃:

factory BvnConsent.fromJson(Map<String, dynamic> json) {
  return BvnConsent(
    consentId: json['consent_id'] is String ? json['consent_id'] : null,
    customerDetails: json['customer_details'] is Map 
        ? CustomerDetails.fromJson(json['customer_details']) 
        : null,
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 23:37:08