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

Flutter ListViewBuilder报错:'String'不是'index'所需的'int'类型

错误原因与修复方案

核心问题

你遇到的type 'String' is not a subtype of type 'int' of 'index'错误,本质是在需要整数索引的场景中传入了字符串值,大概率和你处理Firebase数据、使用ListView.builder的方式有关。

常见触发场景及修复

1. 直接用Firebase的字符串Key当索引

Firebase Realtime Database返回的分类数据通常是Map<String, dynamic>(key是字符串类型的节点ID),如果你直接把这个Map当列表用,或者用它的key作为ListView.builder的索引,就会报错。

修复代码示例:
把Map的取值转换成List再使用:

// 从Firebase获取数据后
final dataSnapshot = await FirebaseDatabase.instance.ref('categories').get();
if (dataSnapshot.exists) {
  // 将Map的值转为List,这样就能用整数索引访问
  final categoryList = (dataSnapshot.value as Map<String, dynamic>).values.toList();
  // 后续用categoryList给ListView.builder提供数据
}

2. ListView.builder的索引使用错误

确保itemCount是列表的长度(整数),且itemBuilder里的index(整数参数)被正确用来访问列表元素:

ListView.builder(
  itemCount: categoryList.length, // 必须是整数,对应列表的实际长度
  itemBuilder: (context, index) {
    // 用整数index访问列表元素,不要用字符串
    final currentItem = categoryList[index];
    return ListTile(title: Text(currentItem['name']));
  },
)

3. 分类列表的数据源类型错误

检查你的分类列表是不是List类型——如果是Map类型,绝对不能直接给ListView.builder用,必须先转成List。可以通过打印验证:

print(categoryList.runtimeType); // 应该输出类似List<dynamic>的结果

快速排查技巧

  • 打印你用来给ListView提供数据的变量类型和内容,确认是标准List
  • 检查所有访问列表元素的代码,确保没有用字符串代替整数索引(比如list['id']这种写法是错的,应该是list[0])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 16:03:11