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

Flutter ListView设置itemCount仍报RangeError索引越界问题排查

Flutter ListView.separated 索引越界问题修复

报错现象

运行列表功能时抛出异常:
RangeError (index): Invalid value: Not in inclusive range 0..39: 42
已确认给ListView.separated配置了itemCount属性,列表共40项时运行完全正常,新增第41条数据后触发上述越界错误。

问题代码

ListView.separated(
  physics: const BouncingScrollPhysics(),
  shrinkWrap: true,
  itemBuilder: (BuildContext context, int index) {
    print('num : ${episode[index]!.episodeNum.toString()}');
    final data = episode[index];
    if (type == adminPanel) {
      return Stack(
        children: [
          EpisodeBar(
            episode: index + 1,
            caption: data!.caption,
            time: data.time,
            colorTheme: AppThemeColors.colorList[index],
            duration: data.time,
            link: data.link,
          ),
          Column(
            children: [
              EditButton(data: data, courseID: crsId),
              const SizedBox(height: 20),
              DeleteButton(eps: _eps, data: data, courseID: crsId),
            ],
          )
        ],
      );
    }
    log('${snapshot.data!.length}');
    return EpisodeBar(
      episode: data!.episodeNum.toString(),
      caption: data.caption,
      time: data.time,
      colorTheme: AppThemeColors.colorList[index],
      duration: data.time,
      link: data.link,
    );
  },
  itemCount:snapshot.data!.length,
  separatorBuilder: (BuildContext context, int index) {
    if (type == adminPanel) {
      return const Divider(
        thickness: 1,
        height: 40,
      );
    }
    return const SizedBox(height: 20);
  },
);

运行报错截图

运行报错截图

问题根因

报错提示索引42不在0-39的合法区间,说明被索引的列表实际长度只有40,但是构建逻辑尝试访问第43个元素(索引从0开始),核心问题有两个:

  • 数据源长度不统一:itemCount绑定的是snapshot.data!.length,但是itemBuilder里实际取渲染数据用的是episode列表,两个列表长度不同步。新增数据后snapshot.data拿到了最新的更长的列表长度(43),但是episode列表没有同步更新,仍然只有40项,当index增长到42时,访问episode[index]直接触发越界。40项时两个列表长度刚好一致,所以不会报错。
  • 固定长度颜色列表索引风险:代码中直接用index访问AppThemeColors.colorList,如果这个颜色列表是固定写死的40个颜色,当列表项超过40时,index超过39也会触发越界。

修复方案

  • 统一数据源:如果渲染逻辑用episode列表取数据,就把itemCount改成episode.length,保证itemCount和实际被索引的渲染列表长度完全一致;如果要使用snapshot.data作为数据源,就把itemBuilder里所有episode[index]的调用改成snapshot.data![index],不要混用两个数据源。新增数据后要保证两个列表的同步更新逻辑正确。
  • 修复颜色列表索引逻辑:固定长度的颜色列表不要直接用index取值,改用取模运算循环取色,不管列表多长都不会越界:
// 替换原来的 AppThemeColors.colorList[index]
colorTheme: AppThemeColors.colorList[index % AppThemeColors.colorList.length],

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 09:54:23