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用字符串作为索引,直接触发该报错。
修复方案
- 先确认接口返回格式,你可以在APIClient的
jsonDecode后添加日志确认类型:
final peopleJson = jsonDecode(peopleResponse.body); print(peopleJson.runtimeType); // 输出为List<dynamic>即可确认是该问题
- 如果确认返回的是数组,取数组第一个元素传入fromJson即可:
// 修改APIClient的返回逻辑 return People.fromJson(peopleJson[0]);
- 可选的防御性优化:给charId字段添加强制类型转换,避免后续接口返回字符串格式的id时报错:
// 修改People.fromJson方法 static People fromJson(dynamic json) { return People( charId: int.parse(json['char_id'].toString()), ); }
内容的提问来源于stack exchange,提问作者Graaggas
相关产品推荐
相关产品推荐

