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中错误的键名 |
|---|---|
number | badgeNumber |
stage | status |
dob | birthDay |
phoneNumber | phone |
mId | managerId |
修复后的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
相关产品推荐
相关产品推荐

