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

Flutter中DropdownSearch结合Drift实现食材表搜索功能的求助

Flutter中DropdownSearch结合Drift实现食材表搜索功能的求助

嘿,我来帮你搞定这个需求!你现在是在Flutter项目里用Drift管理食材数据库,想搭配DropdownSearch组件实现带搜索的下拉选择功能对吧?看你已经把Ingredients表的结构定义好了,那咱们一步步来实现~

首先,你得先在Drift的数据库类里加一个支持搜索的查询方法,这样能根据用户输入的关键词从数据库里捞匹配的食材:

// 假设你的数据库类是MyDatabase,记得替换成你实际的类名
class MyDatabase extends _$MyDatabase {
  // ... 这里是你的数据库初始化代码,比如构造函数、schemaVersion这些

  // 新增:获取匹配搜索词的食材列表
  Future<List<Ingredient>> fetchMatchingIngredients(String? searchKeyword) async {
    if (searchKeyword == null || searchKeyword.trim().isEmpty) {
      // 如果没有搜索词,就返回所有食材
      return select(ingredients).get();
    } else {
      // 模糊搜索食材名称或编码,忽略大小写的话可以加collate参数
      final keyword = '%${searchKeyword.trim()}%';
      return (select(ingredients)
            ..where((table) => table.ingredientName.like(keyword, collate: Collate.noCase)
                .or(table.code.like(keyword, collate: Collate.noCase))))
          .get();
    }
  }
}

接下来就是配置DropdownSearch组件啦,核心是用asyncItems属性,根据用户输入的搜索词动态从Drift拉取数据,同时开启搜索框、设置显示样式:

DropdownSearch<Ingredient>(
  // 关键:根据搜索词异步获取匹配的食材
  asyncItems: (String? filter) => MyDatabase.instance.fetchMatchingIngredients(filter),
  // 定义下拉项显示的文本,把食材名称和编码都展示出来更直观
  itemAsString: (Ingredient ingredient) => '${ingredient.ingredientName} (编码:${ingredient.code})',
  // 下拉框的装饰样式
  dropdownDecoratorProps: DropDownDecoratorProps(
    dropdownSearchDecoration: InputDecoration(
      labelText: '选择食材',
      hintText: '输入名称或编码搜索',
      border: OutlineInputBorder(),
    ),
  ),
  // 开启搜索框
  showSearchBox: true,
  // 搜索框的样式配置
  searchFieldProps: TextFieldProps(
    decoration: InputDecoration(
      hintText: '输入关键词搜索...',
      prefixIcon: Icon(Icons.search),
      border: OutlineInputBorder(),
    ),
  ),
  // 选中食材后的回调处理
  onChanged: (Ingredient? selectedIngredient) {
    if (selectedIngredient != null) {
      // 这里写你选中食材后的逻辑,比如赋值给变量、更新UI之类的
      print('选中了:${selectedIngredient.ingredientName},碳水:${selectedIngredient.glucides}');
    }
  },
  // 可选:设置默认选中项
  // selectedItem: defaultIngredient,
)

最后给你提几个小注意点:

  • 确保你的Drift数据库实例是全局可访问的,或者用Provider、Riverpod这类状态管理工具注入,避免重复初始化
  • 如果食材数据量很大,建议给ingredientName和code字段加索引,能提升搜索查询的速度
  • 要是需要更精准的搜索,可以调整like的匹配规则,比如去掉前后的%只匹配开头,或者结合其他字段

备注:内容来源于stack exchange,提问作者ABDELAZIZ RASS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 17:13:12