Flutter中使用Getx时,如何让DropdownButtonFormField显示提示文本而非初始值
步骤1:修改Getx控制器
将selectedCity的初始值从固定字符串改为null,让控件初始状态处于未选中状态,为显示提示文本创造条件:
class DropdownMenuController extends GetxController { // 改为可空的RxString,初始值为null final selectedCity = RxString?(); final List<String> cityList = [ 'Berlin', 'Paris', 'Rome', ]; void setSelectedCity(String value) { selectedCity.value = value; } }
步骤2:更新InputDecoration,添加提示文本
给kDropdownMenuDecoration补充hintText,作为未选择时的提示内容:
InputDecoration kDropdownMenuDecoration = InputDecoration( hintText: '请选择城市', // 添加提示文本 contentPadding: EdgeInsets.fromLTRB(10, 2, 10, 2), border: OutlineInputBorder( borderRadius: BorderRadius.all( Radius.zero, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.all( Radius.zero, ), borderSide: BorderSide(color: Colors.grey), ), );
步骤3:调整DropdownButtonFormField配置
- 动态设置
value属性,仅当selectedCity有值时才绑定选中项 - 添加
validator回调,实现未选择时的警告提示
class InfoDropdown extends StatelessWidget { const InfoDropdown({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final DropdownMenuController controller = Get.find<DropdownMenuController>(); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.fromLTRB(10, 2, 10, 2), child: Text( 'City', style: TextStyle( color: Colors.indigo, ), ), ), Padding( padding: const EdgeInsets.fromLTRB(10, 2, 10, 20), child: SizedBox( height: 50, child: Obx(() => DropdownButtonFormField<String>( decoration: kDropdownMenuDecoration, onChanged: (newValue) { if (newValue != null) { controller.setSelectedCity(newValue); } }, // 仅当selectedCity有值时设置选中项,空值时显示提示文本 value: controller.selectedCity.value, validator: (value) { if (value == null || value.isEmpty) { return '请选择一个城市'; // 未选择时的警告提示 } return null; }, items: controller.cityList.map((selectedItem) { return DropdownMenuItem( value: selectedItem, child: Text(selectedItem), ); }).toList(), )), ), ), ], ); } }
额外说明
- 使用
Get.find<DropdownMenuController>()获取控制器实例,符合Getx依赖管理规范 - 初始状态下控件会显示
hintText,用户未选择城市时,表单验证会触发警告提示 - 只有用户主动选择城市后,
selectedCity才会赋值,控件才会显示选中的城市名称
内容的提问来源于stack exchange,提问作者Alp Karky
相关产品推荐
相关产品推荐

