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

使用Bloc的Flutter API请求代码抛出“索引越界”错误求助

问题根源

你遇到的「index out of range」错误,核心原因是**GridView的itemBuilder中,无论过滤状态如何,都提前尝试访问了两个列表的对应索引**:

  • 当tempDrinksList为空时,itemCount取的是drinksList的长度,但代码里依然执行了final filterDrinks = state.tempDrinksList[index];,空列表无法访问任何索引,直接触发越界错误。
  • 即使tempDrinksList不为空,若过滤后的列表长度与原drinksList不一致,提前访问另一个列表的索引也可能引发问题。
修复方案

将列表元素的获取逻辑放到对应的条件分支内,或者用统一变量存储当前要展示的饮品,避免无意义的索引访问:

优化后的GridView.builder代码

GridView.builder(
  physics: NeverScrollableScrollPhysics(),
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    crossAxisCount: 2,
    crossAxisSpacing: 40,
    mainAxisSpacing: 20,
    childAspectRatio: 0.7,
  ),
  shrinkWrap: true,
  padding: EdgeInsets.symmetric(vertical: 30, horizontal: 25),
  itemCount: state.tempDrinksList.isEmpty 
      ? state.drinksList.length 
      : state.tempDrinksList.length,
  itemBuilder: (context, index) {
    // 统一获取当前要展示的饮品,避免冗余索引访问
    final currentDrink = state.tempDrinksList.isNotEmpty 
        ? state.tempDrinksList[index] 
        : state.drinksList[index];
    return buildGridContainer(currentDrink);
  },
);

额外注意事项

  1. 初始化状态兜底:确保HomeState中drinksList和tempDrinksList的初始值为空列表([]),而非null,避免API请求未返回时出现空指针或越界问题。
  2. 加载状态处理:在Bloc的初始状态中,将status设为HomeStatus.loading,并在UI中根据状态显示加载组件(如CircularProgressIndicator),避免数据未就绪时渲染空列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:55:15