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

Flutter报错:type 'List<dynamic>' is not a subtype of type 'List<Item>' 求助

问题解决:type 'List' is not a subtype of type 'List'

这个错误的核心原因是你直接把接口返回的动态列表赋值给了List<Item>类型变量,两者类型不匹配。接口返回的JSON数组解析后是List<dynamic>,每个元素是Map<String, dynamic>,必须手动转换成Item实例才能赋值。

修复步骤

1. 修改getData方法完成类型转换

替换原来的赋值逻辑,遍历解析每个JSON对象为Item实例:

getData() async {
  var url = 'http://xxxxxxxxxx/flutter/logement_concret.php';
  print(url);
  final response = await http.get(Uri.parse(url));
  // 先解析为动态列表,再逐个转成Item对象
  List<dynamic> tempList = json.decode(response.body);
  item = tempList.map((json) => Item.fromJson(json)).toList();
  print(item);
  // 调用setState触发UI刷新,否则列表不会更新
  setState(() {});
  return item;
}

2. 修复价格显示的字符串插值错误

当前价格文本的写法无法正确解析变量,修改为:

Text(
  "\$${item[index].price}/month",
  style: const TextStyle(
      fontWeight: FontWeight.bold,
      fontSize: 20.0,
      overflow: TextOverflow.ellipsis),
),

额外优化建议

  • 增加异常处理:网络请求和JSON解析可能失败,添加try-catch避免崩溃:
getData() async {
  try {
    var url = 'http://xxxxxxxxxx/flutter/logement_concret.php';
    print(url);
    final response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      List<dynamic> tempList = json.decode(response.body);
      item = tempList.map((json) => Item.fromJson(json)).toList();
      setState(() {});
    } else {
      print('请求失败:${response.statusCode}');
    }
  } catch (e) {
    print('解析或请求出错:$e');
  }
  return item;
}
  • 空安全处理:访问item[index]的属性时,用空值运算符避免空指针,比如item[index].thumb_url ?? ''。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:45:39