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

Flutter/Dart:保存List到缓存时类型不匹配错误求助

Flutter/Dart缓存存储错误修复方案

问题详情

终端打印incidentList数据正常,但调用WriteCache.setListString保存时出现类型不匹配错误:

Error: The argument type 'List<Map<String, dynamic>>' can't be assigned to the parameter type 'List'.

错误指向代码行:

await WriteCache.setListString(key: 'cache4', value: incidentList);

相关业务逻辑:通过接口请求解析得到List<Map<String, dynamic>>类型的incidentList,需要存入缓存,但类型不符合setListString的参数要求。当前打印结果为一行式的List,期望每个字段换行展示。

错误原因

WriteCache.setListString方法仅接受List<String>类型的参数,而你传入的incidentList是List<Map<String, dynamic>>,两者类型不兼容,导致编译报错。

修复方案

方案1:将Map列表转为JSON字符串列表存储

把incidentList中的每个Map对象通过jsonEncode转换为JSON字符串,生成符合要求的List<String>:

// 转换类型
List<String> incidentStrList = incidentList.map((item) => jsonEncode(item)).toList();
// 存入缓存
await WriteCache.setListString(key: 'cache4', value: incidentStrList);

读取缓存时,再将每个JSON字符串转回Map:

List<String> cachedStrList = await ReadCache.getListString(key: 'cache4');
List<Map<String, dynamic>> cachedIncidents = cachedStrList.map((str) => jsonDecode(str) as Map<String, dynamic>).toList();

方案2:将整个列表序列化为单个JSON字符串存储

如果不需要单独操作列表中的每个元素,可直接将整个incidentList序列化为单个JSON字符串,用setString方法存储:

// 序列化整个列表并存储
await WriteCache.setString(key: 'cache4', value: jsonEncode(incidentList));

读取时解析回原列表:

String cachedStr = await ReadCache.getString(key: 'cache4');
List<Map<String, dynamic>> cachedIncidents = jsonDecode(cachedStr) as List<Map<String, dynamic>>;

额外优化:实现期望的打印格式

要让打印结果按字段换行展示,可遍历列表逐个格式化输出:

for (var incident in incidentList) {
  print('Code: ${incident['Code']},');
  print('Description: ${incident['Description']},');
  print('Organisation Unit: ${incident['Organisation Unit']},');
  print('Date Reported: ${incident['Date Reported']},\n');
}

内容的提问来源于stack exchange,提问作者JoshuaaMarkk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 06:54:07