Flutter JSON解析报错:media字段非空却解析为null,如何修复?
修复Flutter JSON解析中media字段为null的错误
错误原因
报错type 'Null' is not a subtype of type 'Iterable'直接指向Product.fromJson里解析media的代码:List.from(json['media'])。即便你确认API返回的media大多有数据,但可能存在个别场景下该字段为null,而List.from()无法接收null作为参数,导致类型转换失败。
修复方案
修改Product类的fromJson方法,给media字段添加空值安全处理,确保无论API返回的media是null还是有效数组,都能正确解析:
class Product { late final int id; late final String name; late final String categoryName; late final List<Media> media; Product({ required this.id, required this.name, required this.categoryName, required this.media, }); Product.fromJson(Map<String, dynamic> json){ id = json['id'] as int; name = json['name'] as String; categoryName = json['category_name'] as String; // 修复media解析的空值问题 final mediaJsonList = json['media'] as List?; media = mediaJsonList?.map((e) => Media.fromJson(e as Map<String, dynamic>)).toList() ?? []; } Map<String, dynamic> toJson() { final _data = <String, dynamic>{}; _data['id'] = id; _data['name'] = name; _data['category_name'] = categoryName; _data['media'] = media.map((e)=>e.toJson()).toList(); return _data; } }
额外优化建议
为避免其他字段出现类似类型转换问题,建议给所有fromJson中的字段添加明确的类型断言(比如as int、as String);对于已声明为可空类型的嵌套字段(比如Links中的s3、cdn),保持现有处理即可。
内容的提问来源于stack exchange,提问作者st4tic
相关产品推荐
相关产品推荐

