Flutter应用映射本地JSON实体类时出现List<dynamic>无法强转List<int>异常
Flutter JSON解析类型异常解决方案
异常触发根源
报错堆栈指向TypeMap.fromJson方法中为type3字段赋值的代码行,对应代码为type3: json['type3'] as List<int>。
使用jsonDecode解析JSON文本时,所有嵌套数组结构默认都会被解析为List<dynamic>类型。Dart的强类型检查规则中,List<dynamic>与List<int>不存在直接的子类型兼容关系,无法通过as关键字直接完成强制类型转换,因此会抛出type 'List<dynamic>' is not a subtype of type 'List<int>' in type cast异常。
对比代码中处理type4字段的逻辑可以发现明显差异:处理type4时,你先将JSON中的对应值转为List<dynamic>,再通过map方法逐元素转换为SubTypeMap实例,最终生成的List<SubTypeMap>符合类型要求;而处理type3时,你直接对原始的List<dynamic>做硬转,没有逐元素完成int类型映射,才触发了类型不匹配问题。
修复实现
修改type3字段的赋值逻辑,和type4的处理方式保持一致:先将外层数组转为List<dynamic>,再逐元素转换为int类型,生成符合类型要求的List<int>。
修改后的核心代码片段:
factory TypeMap.fromJson(Map<String, dynamic> json) { final newList = json['type4'] as List<dynamic>; final updatedList = newList.map<SubTypeMap>((item) => SubTypeMap.fromJson(item)).toList(); return TypeMap( type1: json['type1'] as int, type2: json['type2'] as int, // 替换原有的直接强转逻辑 type3: (json['type3'] as List<dynamic>).map((element) => element as int).toList(), type4: updatedList, ); }
- 拓展说明:后续处理其他基础类型嵌套数组(比如
List<String>、List<double>)时,都可以套用相同逻辑,避免直接对List<dynamic>做强转引发同类异常。
内容的提问来源于stack exchange,提问作者MKapp
相关产品推荐
相关产品推荐

