Flutter DropdownMenu搜索触发RangeError(length)问题排查求助
错误原因
你同时开启了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
相关产品推荐
相关产品推荐

