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

Flutter项目GetX组件构建触发RangeError(index:-1)问题排查

解决Flutter中RangeError(index): 无效值:有效取值范围为空:-1的问题

错误详情

═══╡ WIDGETS库捕获异常 ╞═══════════════════════════════════════════════════════════
构建GetX(controller: Instance of 'MzfUsersController', tag: null, has builder, dirty, state: GetXState#a8779(controller: Instance of 'MzfUsersController'))时抛出以下RangeError:
RangeError (index): 无效值:有效取值范围为空:-1

相关错误触发组件:
GetX
路径:file:///D:/flutter_egitim/GedikKaynak-App-versiyon-3/lib/views/portal/home/menu_widget.dart:131:26

调用栈

#0      List.[] (dart:core-patch/growable_array.dart:264:36)
#1      MenuWidget.<anonymous closure>.<anonymous closure> (package:gedik_holding/views/portal/home/menu_widget.dart:138:48)
#2      GetXState.build.<anonymous closure> (package:get/get_state_manager/src/rx_flutter/rx_getx_widget.dart:131:29)
#3      RxInterface.notifyChildren (package:get/get_rx/src/rx_types/rx_core/rx_interface.dart:26:27)
#4      GetXState.build (package:get/get_state_manager/src/rx_flutter/rx_getx_widget.dart:129:53)
#5      StatefulElement.build (package:flutter/src/widgets/framework.dart:4919:27)
#6      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4806:15)
#7      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4977:11)
#8      Element.rebuild (package:flutter/src/widgets/framework.dart:4529:5)
#9      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4787:5)
#10     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4968:11)
#11     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4781:5)

问题根源

设置FormBuilderDropdown的initialValue时,bayiiCodeList.indexWhere((bayi) => bayi.startsWith(GetStorage().read("bayiiUserCode") ?? "1"))返回-1(未找到匹配项),直接用该索引访问bayiiList[-1]触发RangeError。同时onChanged回调中也存在相同风险,无匹配项时会再次报错。

修复方案

  1. 先判断bayiiList和bayiiCodeList是否为空,避免空列表访问
  2. 对indexWhere的结果做校验,返回-1时设置默认值或跳过赋值
  3. onChanged中同样处理索引为-1的情况,防止报错

修复后的代码示例

Padding(
  padding: const EdgeInsets.symmetric(horizontal: 10.0),
  child: GetX<MzfUsersController>(
    init: MzfUsersController(),
    builder: (data) {
      List bayiiList = data.userList;
      List bayiiCodeList = data.userCodes;
      String? initialBayii;

      // 安全处理初始值
      if (bayiiList.isNotEmpty && bayiiCodeList.isNotEmpty) {
        final targetCode = GetStorage().read("bayiiUserCode") ?? "1";
        final matchIndex = bayiiCodeList.indexWhere((bayi) => bayi.startsWith(targetCode));
        initialBayii = matchIndex != -1 ? bayiiList[matchIndex] : bayiiList.firstOrNull;
      }

      return FormBuilderDropdown(
        clearIcon: Container(),
        initialValue: initialBayii,
        onChanged: (value) {
          if (value == null || bayiiList.isEmpty || bayiiCodeList.isEmpty) return;
          final matchIndex = bayiiList.indexWhere((bayi) => bayi.startsWith(value));
          if (matchIndex != -1) {
            Get.put(BayiiController()).changeBayii(bayiiCodeList[matchIndex]);
          }
        },
        icon: Icon(Icons.account_balance),
        name: 'bayii',
        decoration: InputDecoration(
          labelText: 'Bayii',
        ),
        allowClear: true,
        hint: Text('Bayii Seç'),
        validator: FormBuilderValidators.compose([FormBuilderValidators.required(Get.context)]),
        items: bayiiList
            .map((bayii) => DropdownMenuItem(
                  value: bayii,
                  child: Text(
                    '$bayii',
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                  ),
                ))
            .toList(),
      );
    },
  ),
),

内容的提问来源于stack exchange,提问作者Umutcan Bağdu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:25:21