Flutter赋值API数据时报错List<dynamic>不是List<CustomerTransactionDetail>子类型
报错原因与解决方案
报错根因
Dart中jsonDecode解析接口返回的JSON数据后,嵌套的列表默认是List<dynamic>类型,无法直接赋值给声明为List<CustomerTransactionDetail>的强类型字段,必须手动完成类型映射转换。
修复步骤
1. 确保CustomerTransactionDetail模型实现fromJson构造方法
先确认你的模型类已经定义了工厂构造方法用于JSON转模型实例,示例如下:
class CustomerTransactionDetail { // 此处为你的模型自有字段,按实际需求定义 String? transactionId; num? amount; String? createTime; // 构造方法 CustomerTransactionDetail({ this.transactionId, this.amount, this.createTime, }); // JSON转模型的工厂方法 factory CustomerTransactionDetail.fromJson(Map<String, dynamic> json) { return CustomerTransactionDetail( transactionId: json['transaction_id'], amount: json['amount'], createTime: json['create_time'], // 其余字段按实际接口返回的key自行补充 ); } }
2. 修改报错行的赋值逻辑
将原来直接赋值动态列表的代码,替换为遍历转换后的强类型列表:
// 原报错代码 // customerTransactionDetail: customerDetailGet['customer_transaction_detail'], // 替换为如下代码 customerTransactionDetail: (customerDetailGet['customer_transaction_detail'] as List) .map((dynamic item) => CustomerTransactionDetail.fromJson(item as Map<String, dynamic>)) .toList(),
3. 实现列表追加逻辑
如果需要把新获取的交易列表追加到已有列表中,可按如下两种方式处理:
- 方式一:接口请求层处理拼接
先从Provider中取出已有的旧交易列表,和新转换的列表拼接后再赋值给模型字段:
// 先获取Provider中存储的旧交易列表 final oldList = Provider.of<CustomerAndTransactionClassProvider>(context, listen: false).existTransactionList; // 转换新接口返回的交易列表 final newList = (customerDetailGet['customer_transaction_detail'] as List) .map((item) => CustomerTransactionDetail.fromJson(item)) .toList(); // 拼接得到合并后的列表 final mergedList = [...oldList, ...newList]; // 赋值时使用合并后的列表 var customerDetail = CustomerDetail( // 其余字段保持不变 customerTransactionDetail: mergedList, // 其余字段保持不变 );
- 方式二:Provider层处理拼接
直接把转换好的新交易列表传给Provider的addCustomer方法,在方法内部完成新旧列表的追加操作即可。
优化建议
如果接口可能返回空的交易列表,建议增加空安全校验,避免空指针异常:
customerTransactionDetail: (customerDetailGet['customer_transaction_detail'] as List?) ?.map((item) => CustomerTransactionDetail.fromJson(item)) .toList() ?? [],
内容的提问来源于stack exchange,提问作者Yasir Mehmood
相关产品推荐
相关产品推荐

