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

Flutter桌面库存管理系统RangeError索引越界问题求助

问题排查与解决方案

错误原因分析

RangeError (index): Invalid value: Not in inclusive range 0..4: 5 是典型的列表索引越界错误,说明代码尝试访问长度为5的列表的第5个索引(列表索引从0开始,合法范围是0-4)。结合你提供的代码,可能的触发点有两个:


1. 422错误处理逻辑中的索引越界

在addInventory的422状态码分支中,当前代码直接访问errors[errors.keys.elementAt(0)][0],没有做任何空值或长度判断:

  • 如果服务器返回的errors为空,或者某个错误对应的列表为空,就会触发索引越界。
  • elementAt(0)虽然写法合法,但不如直接使用keys.first安全,且缺少前置判断。

修复代码

修改422分支的错误处理逻辑,增加空值与长度校验:

case 422:
  final errors = jsonDecode(response.body)['errors'];
  if (errors != null && errors.isNotEmpty) {
    final firstKey = errors.keys.first;
    final errorList = errors[firstKey];
    if (errorList != null && errorList.isNotEmpty) {
      res.error = errorList[0];
    } else {
      res.error = somethingWentWrong;
    }
  } else {
    res.error = somethingWentWrong;
  }
  break;

2. 循环中列表被意外修改

在getData的setState里,你直接遍历_inventoryList,如果addInventory的异步回调(比如数据插入成功后)会修改_inventoryList的长度,可能导致后续循环的索引越界。

修复代码

先将列表复制到临时变量,再遍历临时变量:

// 在循环前复制列表到临时变量
final tempInventoryList = List.from(_inventoryList);
for (var i = 0; i < tempInventoryList.length; i++) {
    addInventory(
      tempInventoryList[i]['id_kategori'], 
      tempInventoryList[i]['id_gudang'], 
      tempInventoryList[i]['id_brand'], 
      tempInventoryList[i]['nama'], 
      tempInventoryList[i]['parts_no'], 
      tempInventoryList[i]['new_parts'], 
      tempInventoryList[i]['satuan'], 
      tempInventoryList[i]['jumlah_akhir'], 
      0.0,
      0.0,
      tempInventoryList[i]['jumlah_akhir'], 
      tempInventoryList[i]['harga'], 
      tempInventoryList[i]['image'], 
      tanggal,
    ); 
}

3. 辅助排查步骤

如果上述修复后仍有问题,可添加日志定位具体触发点:

// 在循环内添加错误捕获与日志
for (var i = 0; i < tempInventoryList.length; i++) {
  try {
    print('正在处理第$i条库存数据: ${tempInventoryList[i]}');
    await addInventory(/* 参数 */);
  } catch (e, stackTrace) {
    print('处理第$i条数据时出错: $e');
    print('错误栈: $stackTrace');
  }
}

通过日志可以明确是哪条数据或哪个步骤触发了索引越界。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:31:02