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

如何将String类型ID传入ListView.Builder?解决类型不匹配错误

问题解决:Type 'String' is not a subtype of type 'int' of 'index'

你的报错根源并非ListView.builder的索引问题,而是API数据解析逻辑错误,以下是具体问题和修复方案:

核心错误点

  1. API响应解析错误:Valorant API返回结构为{"status":200,"data":[Agent数组]},你在代码中错误地将json.decode(response.body)['data'](已经是Agent数组)再次用字符串索引"data"访问,而List只能用整数索引,这直接触发了类型转换错误。
  2. Agent.fromJson类型转换遗漏:role字段直接赋值为json['role'](Map类型),没有通过Role.fromJson转换为Role对象,会导致后续访问role.displayName时出错。
  3. 冗余错误逻辑:fetchAgents中那段判断data is Map的代码完全无效,属于逻辑混乱,需要删除。

修复后的代码

1. 修正fetchAgents函数

Future<List<Agent>> fetchAgents() async {
  final response = await http.get(Uri.parse('https://valorant-api.com/v1/agents'));

  if (response.statusCode == 200) {
    List<dynamic> jsonResponse = json.decode(response.body)['data'];
    return jsonResponse.map((agentJson) => Agent.fromJson(agentJson)).toList();
  } else {
    throw Exception('Failed to load data');
  }
}

2. 修正Agent.fromJson工厂方法

factory Agent.fromJson(Map<String, dynamic> json) {
  return Agent(
    uuid: json['uuid'],
    displayName: json['displayName'],
    description: json['description'],
    displayIcon: json['displayIcon'],
    displayIconSmall: json['displayIconSmall'],
    isPlayableCharacter: json['isPlayableCharacter'],
    role: Role.fromJson(json['role']), // 转换为Role对象
  );
}

效果说明

修复后,API数据会被正确解析为List<Agent>,ListView.builder可以正常通过整数索引访问列表项,同时String类型的uuid可以正常传递给DetailPage,不会再出现类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:01:21