Flutter中.fromJson实例创建失败:List<dynamic>无法转为List<int>
Flutter购物APP JSON转实体类错误修复
问题场景
基于Flutter 3.3.5开发安卓购物APP,支持扫描EAN条码添加商品至购物车,使用shared_preference持久化Purchase数据。执行以下流程时触发类型转换错误:
- 将Purchase实例转为JSON字符串
- 存入shared_preference容器
- 读取字符串并调用
Purchase.fromJson(jsonString) - 抛出错误:
type 'List<dynamic>' is not a subtype of type 'List<int>' in type cast
问题根源
VSCode自动生成的Purchase.fromMap方法中,错误地将map['items']强制转换为List<int>,但实际该字段是包含ShoppingItem映射的List<dynamic>。由于后续项目需对接REST API生成Purchase实例,必须修复该JSON转实体类的问题。
关键错误代码片段
items: List<ShoppingItem>.from((map['items'] as List<int>).map<ShoppingItem>((x) => ShoppingItem.fromMap(x as Map<String,dynamic>),),)
修复方案
将map['items']的类型强制转换改为List<dynamic>(或直接转为List<Map<String,dynamic>>),再映射为ShoppingItem列表:
// 方案1:修正类型转换,适配动态列表场景 items: List<ShoppingItem>.from((map['items'] as List<dynamic>).map((x) => ShoppingItem.fromMap(x as Map<String, dynamic>)),) // 方案2:明确指定元素类型,适配结构化API数据场景 items: (map['items'] as List<Map<String, dynamic>>).map((x) => ShoppingItem.fromMap(x)).toList()
说明
- 方案1保留原代码结构,仅修正类型转换错误,适配从shared_preference读取的动态列表数据
- 方案2更明确指定列表元素类型,适合对接REST API时的结构化数据场景,能提前发现类型不匹配问题
内容的提问来源于stack exchange,提问作者CSA_Lazarus
相关产品推荐
相关产品推荐

