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

Flutter Bloc报错'String不是int类型index子类型'如何解决

错误原因定位

你遇到的type 'String' is not a subtype of type 'int' of 'index'报错,本质是代码中尝试用String类型的值作为数组/列表的下标索引,而Dart中列表的索引仅支持int类型。结合你提供的代码,最高概率的触发点如下:

  • 你的API接口返回的单条用户数据被包裹在数组中,而非直接返回对象:
    比如接口实际返回格式为[{"char_id": 1, "name": "xxx"}]而非你预期的{"char_id": 1, "name": "xxx"},你调用jsonDecode(peopleResponse.body)得到的是List类型的结果,而非Map类型。此时你直接将数组传入People.fromJson方法,执行json['char_id']时相当于给List用字符串作为索引,直接触发该报错。
修复方案
  1. 先确认接口返回格式,你可以在APIClient的jsonDecode后添加日志确认类型:
final peopleJson = jsonDecode(peopleResponse.body);
print(peopleJson.runtimeType); // 输出为List<dynamic>即可确认是该问题
  1. 如果确认返回的是数组,取数组第一个元素传入fromJson即可:
// 修改APIClient的返回逻辑
return People.fromJson(peopleJson[0]);
  1. 可选的防御性优化:给charId字段添加强制类型转换,避免后续接口返回字符串格式的id时报错:
// 修改People.fromJson方法
static People fromJson(dynamic json) {
  return People(
    charId: int.parse(json['char_id'].toString()),
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 10:51:05