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

Flutter Autocomplete配置:显示label选项,选中后获取对应value

解决方案

要实现Autocomplete显示label(如frNameX)作为建议选项,选中后将对应的value(如engNameX)赋值给query,你需要调整Autocomplete的泛型类型并自定义选项视图,具体修改如下:

核心修改点

  • 将Autocomplete的泛型从String改为Map<String, String>,以便传递完整的条目数据
  • 调整optionsBuilder返回过滤后的完整条目,而非仅返回value
  • 通过optionsViewBuilder定制选项的显示内容,展示label字段
  • 在onSelected中提取选中条目的value赋值给query

修改后的完整代码

Autocomplete<Map<String, String>>(
  optionsBuilder: (TextEditingValue textEditingValue) {
    if (textEditingValue.text.isEmpty) {
      return const Iterable.empty();
    }
    // 保留基于label的过滤逻辑,返回完整的条目对象
    return dataTradList
        .where((element) {
          final label = element['label']!.toLowerCase();
          return label.contains(textEditingValue.text.toLowerCase());
        })
        .toList();
  },
  // 自定义选项视图,显示label字段
  optionsViewBuilder: (context, onSelected, options) {
    return Align(
      alignment: Alignment.topLeft,
      child: Material(
        elevation: 4.0,
        child: SizedBox(
          width: MediaQuery.of(context).size.width,
          child: ListView.builder(
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            itemCount: options.length,
            itemBuilder: (context, index) {
              final option = options.elementAt(index);
              return InkWell(
                onTap: () => onSelected(option),
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  child: Text(option['label']!),
                ),
              );
            },
          ),
        ),
      ),
    );
  },
  onSelected: (selectedOption) {
    setState(() {
      // 取出对应的value赋值给query
      query = selectedOption['value']!;
    });
    print(query);
  },
)

代码说明

  1. 泛型调整:使用Map<String, String>作为Autocomplete的泛型,确保每个选项都携带label和value的完整信息
  2. 选项过滤:optionsBuilder依然基于label字段进行模糊匹配,返回符合条件的完整条目
  3. 选项显示:optionsViewBuilder构建了自定义的下拉选项列表,每个选项展示条目中的label内容
  4. 选中逻辑:onSelected回调中从选中的条目里提取value,赋值给query用于后续API调用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 02:20:12