Flutter:如何为嵌入DropdownButton的FormField添加控制器?
核心思路是在下拉选择的回调中同步更新TextEditingController的内容,同时利用FormField维护表单状态,实现你要的绑定效果。
以下是修改后的完整代码:
List<String> countries = [ 'America', 'Bahrain', 'India', 'Iraq', ]; String? dropdownvalue; ProductController productController = Get.find(); final TextEditingController _countryController = TextEditingController(); // 初始化时同步默认值(可选) @override void initState() { super.initState(); dropdownvalue = 'Bahrain'; _countryController.text = dropdownvalue!; } // 表单中的国家选择字段 FormField<String>( initialValue: dropdownvalue, builder: (FormFieldState<String> state) { return InputDecorator( decoration: InputDecoration( contentPadding: EdgeInsets.only(top: 10), labelText: 'Country', labelStyle: GoogleFonts.poppins( color: Color(0xffb0afaf), fontSize: 20, letterSpacing: 0.6, ), hintText: 'Bahrain', hintStyle: GoogleFonts.lato( color: Color(0xff5c5c5c), fontSize: 17, height: 3, letterSpacing: 0.5, decorationThickness: 6, ), floatingLabelBehavior: FloatingLabelBehavior.always, errorText: state.errorText, // 显示表单错误提示(可选) ), child: DropdownButtonHideUnderline( child: DropdownButton<String>( value: state.value, isExpanded: true, // 让下拉按钮占满输入框宽度 onChanged: (String? newValue) { if (newValue != null) { dropdownvalue = newValue; _countryController.text = newValue; // 同步更新控制器文本 state.didChange(newValue); // 更新FormField状态,支持表单验证/提交 } }, items: countries.map((String country) { return DropdownMenuItem( value: country, child: Text( country, style: GoogleFonts.poppins( color: Color(0xff2e2929), fontWeight: FontWeight.w600, fontSize: 17, letterSpacing: 0.5, ), ), ); }).toList(), ), ), ); }, // 可选:添加表单验证逻辑 validator: (value) { if (value == null || value.isEmpty) { return '请选择国家'; } return null; }, ),
关键修改说明:
- 给
FormField设置initialValue,关联下拉选中的初始值,确保表单状态和下拉值同步 - 在
DropdownButton的onChanged回调中,同步更新_countryController.text,实现控制器与下拉选择的双向绑定 - 调用
state.didChange(newValue)更新FormField状态,保证表单验证、提交等功能正常工作 - 添加
isExpanded: true让下拉按钮占满输入框宽度,视觉上更贴近TextFormField的效果 - 修复了控制器变量名的拼写错误(
_countryConroller→_countryController)
内容的提问来源于stack exchange,提问作者Divya
相关产品推荐
相关产品推荐

