在Flutter中,dropdown_search 是一个流行的第三方插件,用于实现带搜索功能的下拉选择组件。以下是实现步骤和示例代码:
1. 添加依赖
在 pubspec.yaml 文件中添加依赖:
dependencies:
  dropdown_search: ^5.0.2  # 检查最新版本
2. 基本用法
import 'package:dropdown_search/dropdown_search.dart';
DropdownSearch<String>(
  popupProps: PopupProps.menu(
    showSearchBox: true, // 启用搜索框
  ),
  items: ["巴西", "中国", "美国", "日本"], // 数据源
  onChanged: (value) {
    print("选中: $value");
  },
  selectedItem: "中国", // 默认选中项
);
3. 自定义对象列表
class Country {
  final String name;
  final String code;
  
  Country(this.name, this.code);
  
  @override
  String toString() => name; // 重要:定义显示文本
}
DropdownSearch<Country>(
  popupProps: PopupProps.menu(
    showSearchBox: true,
    itemBuilder: (context, item, isSelected) => ListTile(
      title: Text(item.name),
      subtitle: Text(item.code),
    ),
  ),
  asyncItems: (filter) => _loadCountries(), // 异步加载数据
  itemAsString: (item) => item.name, // 指定显示字段
  onChanged: (Country? country) {
    print("选中: ${country?.name}");
  },
);
// 模拟异步数据加载
Future<List<Country>> _loadCountries() async {
  await Future.delayed(Duration(seconds: 1));
  return [
    Country("中国", "CN"),
    Country("美国", "US"),
  ];
}
4. 主要参数说明
- items/- asyncItems: 同步/异步数据源
- popupProps: 弹窗配置- 
- showSearchBox: 显示搜索框
- searchFieldProps: 搜索框属性
- itemBuilder: 自定义列表项
 
- itemAsString: 对象转显示文本
- dropdownBuilder: 自定义下拉框显示
- validator: 表单验证
5. 表单集成
final formKey = GlobalKey<FormState>();
Form(
  key: formKey,
  child: DropdownSearch<String>(
    validator: (value) => value == null ? "必填字段" : null,
    items: ["选项1", "选项2"],
    popupProps: PopupProps.menu(showSearchBox: true),
  ),
)
注意事项
- 对象需重写 toString()或使用itemAsString
- 异步加载时使用 asyncItems
- 可通过 popupProps完全自定义弹窗样式
这个插件提供了高度可定制性,适合需要搜索功能的下拉选择场景。