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

Flutter SearchChoices组件搜索功能失效,列表展示正常问题排查

Flutter SearchChoices 搜索功能失效修复方案

你的问题核心是自定义对象作为DropdownMenuItem的value时,SearchChoices默认无法识别要匹配的搜索字段——它默认会调用对象的toString()方法做匹配,但你的category对象默认的toString()不会返回name字段,导致搜索时找不到对应项。

下面是两种直接有效的修复方式:


方式一:重写自定义对象的toString()方法

在你的Department(假设是该类名)类里重写toString(),让它返回用于搜索的name字段:

class Department {
  final int id;
  final String name;

  Department({required this.id, required this.name});

  // 重写toString,让搜索逻辑能匹配name字段
  @override
  String toString() {
    return name;
  }
}

改完后无需调整原有UI代码,SearchChoices会自动用name匹配搜索词。


方式二:自定义搜索逻辑(更灵活)

如果不想修改对象类,直接在SearchChoices.single中添加searchFn参数,手动指定搜索规则:

SearchChoices.single(
  items: departments.map((category) => DropdownMenuItem(
        value: category,
        child: Text(category.name),
      )).toList(),
  value: _selectedDepartment,
  searchHint: "Select Department",
  // 自定义搜索匹配逻辑
  searchFn: (String keyword, items) {
    return items.where((item) {
      // 匹配category的name字段,忽略大小写提高体验
      return (item.value as Department).name.toLowerCase().contains(keyword.toLowerCase());
    }).toList();
  },
  hint: Text(
    // 修正原代码的空判断和显示逻辑
    _selectedDepartment == null ? "Select Department" : _selectedDepartment.name,
    style: TextStyle(
      fontSize: 12.sp,
      fontWeight: FontWeight.w400,
      color: Color(0XFF747E86),
    ),
  ),
  onChanged: (value) {
    setState(() {
      _selectedDepartment = value;
      // 原代码的_id赋值多余,value本身就是完整的category对象,直接用_selectedDepartment.id即可
      // _selectedDepartment?.id = value?.id;
    });
  },
  isExpanded: true,
  style: TextStyle(
    fontSize: 12.sp,
    fontWeight: FontWeight.w400,
    color: Color(0XFF747E86),
  ),
)

内容的提问来源于stack exchange,提问作者Ahamed habeeb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 07:40:25