DropdownSearch组件需求:搜索时动态调用API获取匹配客户数据
实现DropdownSearch实时调用API搜索客户(而非本地过滤)
当前系统存在超1000个客户名称,现有DropdownSearch组件初始仅加载20条客户数据,搜索操作仅在本地已加载的20条数据内过滤。需求为:每次在搜索框输入关键词时,直接调用API获取最多20条匹配的客户数据,而非本地过滤。
修正方案
1. 调整Provider中的API方法
修改FetchCalibrationcustomer的返回值类型,使其直接返回获取到的客户列表,同时保留状态更新(若其他组件需复用数据):
List<ProductModel> _fetchcustomer = []; List<ProductModel> get fetchcustomer => _fetchcustomer; // 修改返回值为Future<List<ProductModel>>,直接返回搜索结果 Future<List<ProductModel>> FetchCalibrationcustomer(String searchText) async { try { final response = await client.searchRead( "res.partner", [ ['name', 'ilike', searchText], ], [ 'id', 'name', ], context: {}, limit: 20); final extractedData = response.getResult()['records']; // 用map简化列表转换 final List<ProductModel> category = extractedData.map((value) => ProductModel( value['id'], value['name'], )).toList(); // 更新Provider状态(可选,若其他组件需要使用该数据) _fetchcustomer = category; notifyListeners(); return category; } catch (error) { print(error.toString()); rethrow; } }
2. 优化DropdownSearch配置
移除冗余的getcustomer函数,直接在asyncItems中调用Provider的API方法,并开启isFilterOnline确保完全依赖API结果:
Consumer<MaterialPickupProvider>(builder: (context, calibprov, child) { return Container( padding: EdgeInsets.only(left: 2.0.w), width: 70.0.w, decoration: BoxDecoration( border: Border.all(color: Colors.black45), borderRadius: BorderRadius.circular(5.0), ), child: DropdownSearch<ProductModel>( popupProps: PopupProps.menu( showSearchBox: true, // 禁用本地过滤,强制使用API返回的结果 isFilterOnline: true, ), // 实时调用API获取匹配数据 asyncItems: (String filter) => calibprov.FetchCalibrationcustomer(filter), itemAsString: (ProductModel u) => u.name, onChanged: (ProductModel? data) { print('Selected customer: ${data?.name}'); }, dropdownDecoratorProps: DropDownDecoratorProps( dropdownSearchDecoration: InputDecoration( hintText: calibprov.createcustomername ?? "Contact Person", hintStyle: TextStyle( fontSize: 12.sp, fontWeight: FontWeight.bold, color: Colors.black, ), labelStyle: TextStyle( fontSize: 12.sp, fontWeight: FontWeight.bold, color: Colors.black, ), ), ), ), ); }),
核心说明
isFilterOnline: true:该属性会让DropdownSearch跳过本地过滤逻辑,直接展示API返回的所有数据,确保每次搜索都是基于全量客户数据的远程查询。- API方法返回值修正:原方法返回
Future<ProductModel?>不符合业务逻辑,改为返回Future<List<ProductModel>>,直接满足asyncItems的参数要求。 - 简化逻辑链路:移除中间函数
getcustomer,直接在组件中调用Provider的API方法,减少状态传递的冗余,让代码逻辑更直观。
内容的提问来源于stack exchange,提问作者Ahamed habeeb
相关产品推荐
相关产品推荐

