如何在Flutter中实现类似HTML select的下拉选择输入框并获取选中id
Flutter实现类HTML select选择器(绑定value与text)
你可以直接用Flutter官方内置组件实现需求,原生支持显示文本和实际返回值分离,无需引入第三方依赖。
基础实现方案
第一步:修正示例数据
你提供的示例数据第二个元素缺少name键,修正后如下:
List<Map<String, dynamic>> doctors = [ {'id':1,'name':'Jolly'}, {'id':2,'name':'Mat'} ];
第二步:定义状态存储选中值
在State类中定义变量存储选中的医生id:
int? selectedDoctorId;
第三步:编写选择器代码
使用DropdownButton组件构建下拉选择框,核心逻辑是DropdownMenuItem的value绑定需要获取的id,child绑定用户可见的显示文本:
DropdownButton<int>( hint: const Text('请选择医生'), value: selectedDoctorId, // 遍历数据源生成选项 items: doctors.map((doctor) { return DropdownMenuItem<int>( // value绑定实际需要返回的id值 value: doctor['id'], // child配置用户看到的显示文本 child: Text(doctor['name']), ); }).toList(), // 选中时更新状态,此时selectedDoctorId就是你需要的id onChanged: (value) { setState(() { selectedDoctorId = value; }); // 此处可直接使用选中的id debugPrint('选中的医生id:$selectedDoctorId'); }, )
表单场景优化
如果选择器在表单中使用,推荐用DropdownButtonFormField,自带表单验证、样式配置能力:
DropdownButtonFormField<int>( decoration: const InputDecoration( labelText: '选择医生', border: OutlineInputBorder(), ), value: selectedDoctorId, items: doctors.map((doctor) { return DropdownMenuItem<int>( value: doctor['id'], child: Text(doctor['name']), ); }).toList(), onChanged: (value) { setState(() { selectedDoctorId = value; }); }, // 表单验证逻辑 validator: (value) { if (value == null) { return '请选择医生'; } return null; }, )
可选:iOS风格滚轮选择器
如果需要iOS风格的底部滚轮选择效果,可以使用CupertinoPicker实现:
// 触发弹出选择器的方法 void _showDoctorPicker() { showCupertinoModalPopup( context: context, builder: (context) => Container( height: 250, color: Colors.white, child: CupertinoPicker( itemExtent: 40, onSelectedItemChanged: (index) { setState(() { selectedDoctorId = doctors[index]['id']; }); debugPrint('选中的医生id:$selectedDoctorId'); }, children: doctors.map((doctor) => Text(doctor['name'])).toList(), ), ), ); }
提示:如果你的数据源是自定义实体类而非Map,只需要修改对应字段的取值逻辑即可,核心逻辑不变。
内容的提问来源于stack exchange,提问作者Dhia Shalabi
相关产品推荐
相关产品推荐

