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

Flutter JSON转Model报错:type 'Null' is not a subtype of type 'String'

问题原因及解决方案

核心问题分析

抛出type 'Null' is not a subtype of type 'String'异常,主要源于两个问题:

  • 字段名不匹配:模型fromJson方法中使用的JSON键名和接口返回的实际键名不一致,导致读取到null值,部分未做null处理的字段触发类型错误。
  • DateTime解析未处理null:直接对null值调用DateTime.parse(),触发类型转换异常。

具体不匹配的字段对照表

接口JSON键名模型fromJson中错误的键名
numberbadgeNumber
stagestatus
dobbirthDay
phoneNumberphone
mIdmanagerId

修复后的User模型代码

class User {
  String? id;
  String? number;
  String? name;
  String? stage;
  String? sex;
  String? title;
  DateTime? dob;
  String? phoneNumber;
  String? email;
  String? address;
  String? mId;
  DateTime? createdDateTime;
  int? totalRemain;
  int? carryOverRemain;
  DateTime? fromTime;
  DateTime? toTime;

  User({
      this.id,
      this.number,
      this.name,
      this.stage,
      this.sex,
      this.title,
      this.dob,
      this.phoneNumber,
      this.email,
      this.address,
      this.mId,
      this.createdDateTime,
      this.totalRemain,
      this.carryOverRemain,
      this.fromTime,
      this.toTime});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'],
      number: json['number'] ?? "null",
      name: json['name'] ?? "null",
      stage: json['stage'],
      sex: json['sex'] ?? "null",
      title: json['title'] ?? "null",
      // 处理null的DateTime字段
      dob: json['dob'] != null ? DateTime.parse(json['dob']) : null,
      phoneNumber: json['phoneNumber'] ?? "null",
      email: json['email'] ?? "null",
      address: json['address'] ?? "null",
      mId: json['mId'] ?? "null",
      createdDateTime: DateTime.parse(json['createdDateTime']),
      totalRemain: json['totalRemain'],
      carryOverRemain: json['carryOverRemain'],
      fromTime: json['fromTime'] != null ? DateTime.parse(json['fromTime']) : null,
      toTime: json['toTime'] != null ? DateTime.parse(json['toTime']) : null
    );
  }
}

额外优化建议

  • 对于允许为null的字符串字段,建议直接保留null而非赋值为"null"字符串,更符合数据语义,比如number: json['number']即可(模型中number已定义为String?)。
  • 可以使用json_serializable库自动生成模型解析代码,避免手动编写fromJson时出现字段名匹配错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:01:47