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

Flutter DropdownMenu搜索触发RangeError(length)问题排查求助

问题解决:DropdownMenu搜索无匹配时触发RangeError

错误原因

你同时开启了DropdownMenu的enableFilter: true和手动实现过滤逻辑,两者冲突导致索引越界。当先搜索到匹配结果后,组件内部已记录过滤后的有效索引,后续输入无匹配内容时,你手动替换条目列表为包含"No results"的单一条目,但组件内部仍基于之前的索引逻辑计算,导致访问空范围的索引,触发RangeError。

解决方案

关闭组件自带的过滤功能(enableFilter: false),完全使用你自己实现的过滤逻辑即可——你已经通过searchController的文本变化处理了列表过滤,不需要组件重复执行过滤操作。

修改后的代码

products.when(
  data: (productList) { 
    var filteredList = searchController.text.isNotEmpty 
        ? productList
            .where((e) => e.name.contains(RegExp(
                searchController.text,
                caseSensitive: false)))
            .toList()
        : productList.take(5).toList();

    return SizedBox(
      child: DropdownMenu<String?>( 
        textStyle: TextStyle(color: Colors.black),
        inputDecorationTheme: InputDecorationTheme(
          hintStyle: TextStyle(color: Colors.black),
          helperStyle: TextStyle(color: Colors.black),
          labelStyle: TextStyle(color: Colors.black),
        ),
        controller: searchController,
        width: 350,
        hintText: "Search for a product...",
        requestFocusOnTap: true,
        enableFilter: false, // 关闭组件自带过滤
        enabled: selectedProduct == null,
        label: const Text('Select A Product'),
        onSelected: (String? selectedProductName) {
          setState(() {
            selectedProduct = selectedProductName;
          });
        },
        dropdownMenuEntries: filteredList.isEmpty
            ? [
                DropdownMenuEntry<String?>(
                  value: '',
                  label: 'No results found.',
                )
              ]
            : filteredList.map<DropdownMenuEntry<String?>>(
                (ProductModel product) {
                return DropdownMenuEntry<String?>(
                  value: product.id.toString(),
                  label:
                      '${product.name} (${product.location})',
                );
              }).toList(),
      ),
    );
  },
  error: (_, __) => getLoadError(_),
  loading: () => getLoadIndicator(),
),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 16:50:03