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

Flutter中List<dynamic>无法赋值给List<Todo>的问题求助

解决Flutter中List无法转为List的问题

你的错误主要来自两个地方,修正后就能解决问题:

1. 工厂构造函数调用错误

你在map里写的todo.fromJson(item)是错误的,fromJson是Todo类的工厂构造函数,必须通过类名(Todo,首字母大写)调用,而不是你声明的变量名todo。

2. 明确List类型转换

map方法返回的是Iterable<Todo>,直接调用toList()有时会被Dart推断为List<dynamic>,需要明确类型转换。

修正后的完整getCases方法

final String apiUrl = "https://jsonplaceholder.typicode.com/todos";

Future<List<Todo>> getCases() async {
  Response res = await get(Uri.parse(apiUrl));

  if (res.statusCode == 200) {
    List<dynamic> body = jsonDecode(res.body);
    // 用类名调用fromJson,并明确item类型
    List<Todo> todos = body
        .map((item) => Todo.fromJson(item as Map<String, dynamic>))
        .toList();
    return todos;
  } else {
    throw "Failed to load cases list";
  }
}

另一种类型转换方式

也可以使用cast<Todo>()来强转List类型:

List<Todo> todos = body
    .map((item) => Todo.fromJson(item as Map<String, dynamic>))
    .toList()
    .cast<Todo>();

额外健壮性建议

为了避免接口返回异常数据导致崩溃,建议在Todo.fromJson中增加空值处理:

factory Todo.fromJson(Map<String, dynamic> json) {
  return Todo(
      id: json["id"] as int? ?? 0,
      title: json["title"] as String? ?? "",
      completed: json["completed"] as bool? ?? false);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:06:23