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

Flutter中数据转JSON时出现‘type 'Null' is not a subtype of type 'String'’错误的解决方案咨询

解决Flutter Model转JSON时的Null is not a subtype of String错误

错误原因拆解

你的问题主要来自三个核心问题:

  1. 强制解包空值:MainModel.toJson()里的amenities!.map(...)使用!强制解包,如果amenities为null(比如服务器未返回该字段),会直接触发空指针相关错误。
  2. 未处理服务器返回的null字段:AmenitiesModel的name和type都是非空String,但如果服务器返回的JSON里这两个字段为null,直接赋值会导致Model字段存null,后续转JSON时就会抛出Null is not a subtype of String。
  3. 代码笔误:MainModel.fromJson里出现了类定义中不存在的id和user字段,会导致编译错误。

具体修复步骤

1. 修正MainModel.fromJson的笔误

先删掉类中不存在的字段赋值,确保代码编译通过:

factory MainModel.fromJson(Map<String, dynamic> json) => MainModel(
      name: json['name'] ?? '', // 提前处理name可能为null的情况
      amenities: json['amenities'] != null 
          ? List<AmenitiesModel>.from(json['amenities'].map((item) => AmenitiesModel.fromJson(item)))
          : null,
      devices: json['devices'] != null 
          ? List<DeviceModel>.from(json['devices'].map((item) => DeviceModel.fromJson(item)))
          : null,
      photos: json['gallery'] != null 
          ? List<PhotoModel>.from(json['gallery'].map((item) => PhotoModel.fromJson(item)))
          : null,
    );

2. 修复AmenitiesModel的空字段问题

针对服务器可能返回null的字段,要么改为可空类型,要么设置默认值:

class AmenitiesModel {
  String? name; // 允许name为null(根据业务调整)
  final String type; // 确保type非空,给默认值兜底

  AmenitiesModel({required this.type, this.name});

  factory AmenitiesModel.fromJson(Map<String, dynamic> json) {
    return AmenitiesModel(
      type: json['type'] ?? '', // 服务器返回null时用空字符串兜底
      name: json['name'], // 可空字段直接接收null
    );
  }

  Map<String, dynamic> toJson() {
    return {
      if (type == 'other' && name != null) 'name': name, // 仅当name非空时才加入JSON
      'type': type,
    };
  }
}

如果业务上type绝对不能为null,也可以用json['type']!断言,但前提是要确保服务器一定会返回该字段,否则还是会报错。

3. 修复MainModel.toJson的强制解包问题

把amenities!.map改成可选链+默认值,避免空指针:

Map<String, dynamic> toJson() {
  return {
    'name': name,
    // 若amenities为null,返回空数组(或根据后端需求返回null)
    'amenities': amenities?.map((e) => e.toJson()).toList() ?? [],
    'devices': devices?.map((e) => e.toJson()).toList(),
    'gallery': photos?.map((e) => e.toJson()).toList(),
  };
}

如果后端允许amenities为null,直接保留amenities?.map(...)即可,无需加?? []。


额外优化建议

  • 推荐使用json_serializable或freezed这类代码生成工具,自动处理fromJson/toJson逻辑,减少手动编写的错误,同时自动适配空安全规则。
  • 调试时可以打印Model实例的字段值,定位具体是哪个字段为null导致的转换错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 16:17:37