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

Flutter/Dart类型转换错误:String无法转为List<int>?

问题根源

你打印出来的[1,2,3]其实是字符串类型,并非真正的List<int>。接口返回的JSON里,open_days字段大概率是被序列化为带引号的字符串数组(比如"[1,2,3]"),看起来像数组,但实际类型是String,直接赋值自然会触发类型不匹配错误。

解决方法

方法1:把字符串解析成整数列表

如果json['open_days']确实是字符串,手动转成List<int>:

List<int>? openDays;

BarModel.fromMap(Map<String, dynamic> json) {
  barId = json['bar_id'];
  barName = json['bar_name'];
  barAddress = json['bar_address'];
  
  final openDaysRaw = json['open_days'];
  if (openDaysRaw is String) {
    // 去掉首尾的[],按逗号分割后转成int
    openDays = openDaysRaw.substring(1, openDaysRaw.length - 1)
        .split(',')
        .map((item) => int.parse(item.trim()))
        .toList();
  } else if (openDaysRaw is List) {
    // 万一真的是列表,直接转类型
    openDays = openDaysRaw.cast<int>();
  }
}

方法2:排查接口或序列化逻辑

如果接口本应返回数组,那可能是后端返回格式错误,或者你这边的JSON解析出了问题。先确认字段的实际类型:

print(json['open_days'].runtimeType); // 打印出来看是String还是List

要是序列化的问题,检查是否用了jsonDecode(response.body)来解析响应,别直接把响应字符串当Map用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:34:58