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

出现NoSuchMethodError: Class 'List<dynamic>' has no instance method 'cast'报错如何解决

报错原因
  • 你的API接口返回的JSON根结构是文章数组,jsonDecode()执行后得到的结果类型为List<dynamic>,但你调用的.cast<String,dynamic>()是Map类型才支持的方法,对List调用该不存在的方法就会触发这个报错。
修复代码

直接调整解析逻辑即可:

List<Article> posts;
final response = await http.get(Uri.parse("$SERVER_IP/api/articles/?format=json"),
  headers: <String, String>{"Authorization" : "Token ${globaltoken}"},);
// 先拿到解析后的动态数组
final List<dynamic> parsedList = jsonDecode(utf8.decode(response.bodyBytes));
// 遍历数组每个元素转成Article对象
posts = parsedList.map<Article>((json) => Article.fromJSON(json as Map<String,dynamic>)).toList();
return posts;
额外优化建议
  • 增加类型判断避免异常:如果后端有可能返回非数组结构的错误响应,可以提前加一层校验
final decodeResult = jsonDecode(utf8.decode(response.bodyBytes));
if (decodeResult is! List) {
  // 此处可根据业务需求处理错误,比如返回空列表、抛出业务异常
  return [];
}
final parsedList = decodeResult;
// 后续转换逻辑和上面一致
  • 也可以用cast方法先统一转换数组元素类型,写法更简洁:
posts = parsedList.cast<Map<String,dynamic>>().map<Article>((json) => Article.fromJSON(json)).toList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 23:06:02