You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 05:40:22