如何获取Flutter dropdown_search组件选中项ID以提交表单
问题描述
我正在使用Flutter的dropdown_search组件(版本:dropdown_search: ^3.0.1),已实现从API拉取数据并展示,但遇到两个问题:
- 切换下拉选项时无法获取选中项的ID,无法用于表单提交
- 将下拉组件类型改为对象时会报错

解决方案
核心问题是当前将items转换为字符串列表,导致只能拿到名称而非完整对象。只需直接用AccountTypeValues作为下拉项类型,配合组件的itemAsString配置指定显示字段,即可获取完整对象并提取ID。
步骤1:修改DropdownSearch组件配置
将组件类型从dynamic改为AccountTypeValues,调整核心参数:
Padding( padding: const EdgeInsets.all(8.0), child: DropdownSearch<AccountTypeValues>( mode: Mode.MENU, // 直接传入AccountTypeValues对象列表,无需转换为名称字符串 items: controller.listAccountTypeModel_.value, showSearchBox: true, dropdownSearchDecoration: const InputDecoration( labelText: "Account Types", hintText: "Different Account Types", ), // 指定下拉项显示的字段为name itemAsString: (AccountTypeValues item) => item.name ?? "", // 回调参数为AccountTypeValues对象,直接提取oid作为ID onChanged: (AccountTypeValues? selectedItem) { print('选中的账户类型ID: ${selectedItem?.oid}'); controller.setAccountTypeId(selectedItem); }, // 初始化选中项需传入对应AccountTypeValues对象,而非字符串 selectedItem: controller.listAccountTypeModel_.value.isNotEmpty ? controller.listAccountTypeModel_.value.firstWhere( (item) => item.name == "Savings", orElse: () => AccountTypeValues(), ) : null, ), ),
步骤2:调整Controller逻辑
去掉冗余的DropdownMenuItem生成逻辑,修改ID保存和校验方法:
// 保存选中的账户类型ID int? selectedAccountTypeId; // 接收选中的AccountTypeValues对象,提取ID保存 void setAccountTypeId(AccountTypeValues? selectedItem) { selectedAccountTypeId = selectedItem?.oid; refresh(); } // 修改校验逻辑,判断是否选中有效项 String? validateAccountType() { if (selectedAccountTypeId == null) { return "请选择账户类型"; } return null; }
步骤3:优化API获取逻辑(以AccountType为例)
简化数据拉取后的处理,无需手动生成下拉选项:
void getAccountType(String url) { print("获取账户类型数据"); try { Get.dialog(const Center( child: SpinKitDualRing( color: Colors.green, lineWidth: 2, ), )); repository.getAccountTypeData(url).then((value) { if (value.accountTypeValues!.isNotEmpty) { print("账户类型数据: ${value.toString()}"); Get.back(); listAccountTypeModel_.value.clear(); listAccountTypeModel_.value.addAll(value.accountTypeValues!); refresh(); } }).onError((error, stackTrace) { print(error.toString()); Get.back(); // 错误处理逻辑 }); } catch (exception) { print(exception.toString()); Get.back(); // 异常处理逻辑 } }
内容的提问来源于stack exchange,提问作者jonah rimsy
相关产品推荐
相关产品推荐

