如何实现Flutter Autocomplete无匹配选项时支持输入自定义值
实现方案
核心逻辑是先获取匹配的已有选项,判断无完全匹配项时追加自定义新增选项,选中时做对应业务处理即可,完整修改后的代码如下:
// 示例品牌列表,放在你对应的State/全局作用域即可 List<String> brandsList = ['华为', '小米', '苹果']; Autocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { final inputText = textEditingValue.text.trim(); if (inputText.isEmpty) { return const Iterable<String>.empty(); } // 过滤出包含输入内容的已有品牌 final matchedOptions = brandsList.where((String option) { return option.toLowerCase().contains(inputText.toLowerCase()); }).toList(); // 校验是否存在和当前输入完全匹配的品牌 final hasExactMatch = brandsList.any( (brand) => brand.toLowerCase() == inputText.toLowerCase() ); // 无完全匹配时追加新增选项 if (!hasExactMatch) { matchedOptions.add("将$inputText作为新品牌添加"); } return matchedOptions; }, onSelected: (String selection) { // 识别新增选项做对应处理 if (selection.startsWith("将") && selection.endsWith("作为新品牌添加")) { final newBrand = selection.replaceAll("将", "").replaceAll("作为新品牌添加", "").trim(); // 可选:把新品牌加入列表,后续可直接匹配选中 if (!brandsList.contains(newBrand)) { brandsList.add(newBrand); } // 这里补充你自己的业务逻辑,比如存储新品牌到后端/本地 print('新增品牌: $newBrand'); return; } // 已有品牌选中逻辑 print('选中已有品牌: $selection'); }, )
可选优化点
- 可以通过
optionsViewBuilder参数自定义选项样式,给新增选项加+号标识、不同背景色,和普通选项做视觉区分,提升用户体验 - 完全匹配的判断规则可根据业务调整,比如是否区分大小写、是否忽略特殊字符
- 如果需要输入为空时展示全部品牌选项,删除
inputText.isEmpty的判断直接返回brandsList即可
内容的提问来源于stack exchange,提问作者Mafaza SP
相关产品推荐
相关产品推荐

