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

Flutter中AnimatedList无法删除最后一项问题求助

AnimatedList删除最后一项触发RangeError的修复方案

问题原因

删除最后一个待办项时抛出RangeError (index): Invalid value: Valid value range is empty: 0,本质是removeItem的builder回调函数在动画执行阶段才会调用,但此时你已经通过setState修改了数据源db.dailyList,列表变为空后,回调里访问db.dailyList[index]必然触发索引越界。

修复方案

在调用removeItem前先缓存要删除项的所有数据,让动画回调直接使用缓存的数据,而非实时访问已修改的列表:

// delete goal
void deleteGoal(int index) {
  if (db.dailyList.isEmpty) {
    return;
  }
  // 缓存要删除的项数据,避免后续访问已修改的列表
  final deletedItem = db.dailyList[index];
  _listKey.currentState!.removeItem(index, (context, animation) {
    return FadeTransition(
      opacity: animation,
      child: Tile(
        title: deletedItem[0],
        goalAchieved: deletedItem[1],
        onChanged: (value) => {checkBoxChanged(value, index), achievedGoal(index)},
        deleteFunction: (context) => deleteGoal(index),
      ),
    );
  });
  setState(() {
    db.dailyList.removeAt(index);
    for (int i = index; i < db.dailyList.length; i++) {
      db.dailyList[i][2] = i;
    }
  });
  db.updateDatabase();
}

补充说明

  • 缓存deletedItem后,无论列表后续如何修改,动画都能正确获取到删除项的原始数据,彻底避免索引越界问题。
  • 如果Tile组件在动画过程中仍可交互,建议临时禁用其删除/勾选功能,防止因索引变化引发其他异常,但当前报错的核心问题已通过缓存数据解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:45:32