Flutter json_annotation:User模型中Milestone列表为null的问题排查
问题排查与解决方案
1. 检查User模型fromJson的数组解析逻辑
最常见的问题是未正确将JSON数组转换为Milestone实例列表。如果直接赋值而不调用Milestone的fromJson方法,会因类型不匹配导致milestones最终为null。
错误示例:
class User { String? firstName; String? lastName; List<Milestone>? milestones; User.fromJson(Map<String, dynamic> json) { firstName = json['first_name']; lastName = json['last_name']; // 未转换类型,直接赋值导致类型不匹配 milestones = json['milestones']; } }
正确写法:
class User { String? firstName; String? lastName; List<Milestone>? milestones; User.fromJson(Map<String, dynamic> json) { firstName = json['first_name']; lastName = json['last_name']; // 遍历数组并逐个转换为Milestone实例 if (json['milestones'] != null) { milestones = (json['milestones'] as List) .map((item) => Milestone.fromJson(item)) .toList(); } } }
2. 确认Milestone的fromJson方法正确性
如果Milestone的解析逻辑出错,会导致单个实例创建失败,进而整个列表为null。重点检查Unix时间转换逻辑,注意处理空值和时间戳单位(秒/毫秒)。
示例正确的Milestone解析:
class Milestone { int? id; int? userId; String? title; DateTime? startDate; DateTime? endDate; int? notified; Milestone.fromJson(Map<String, dynamic> json) { id = json['id']; userId = json['user_id']; title = json['title']; // 秒级时间戳需转毫秒,再转换为DateTime startDate = json['start_date'] != null ? DateTime.fromMillisecondsSinceEpoch(json['start_date'] * 1000) : null; endDate = json['end_date'] != null ? DateTime.fromMillisecondsSinceEpoch(json['end_date'] * 1000) : null; notified = json['notified']; } }
3. 验证JSON结构匹配性
确认API返回的JSON外层是否有user包裹,比如你提供的示例是user: {...},解析时需正确取到内层的用户数据,而非直接解析外层Map。
错误示例:
// API返回{"user": {...}},但直接解析外层 User user = User.fromJson(response.data);
正确写法:
// 需先取出内层user对象再解析 User user = User.fromJson(response.data['user']);
4. 空安全场景下的边界处理
如果使用空安全语言(如Dart 2.12+),要确保正确处理空数组的情况,避免API返回空数组[]时milestones被赋值为null:
milestones = (json['milestones'] as List?) ?.map((item) => Milestone.fromJson(item)) .toList() ?? [];
5. 调试打印原始JSON
解析前打印API返回的原始数据,确认milestones字段存在且有值,避免因字段名拼写错误(比如少写s成milestone)导致解析失败:
print('原始JSON数据:${response.data}');
内容的提问来源于stack exchange,提问作者Harris
相关产品推荐
相关产品推荐

