如何为Flutter TextField组件添加下拉菜单?
为TextField添加下拉菜单的解决方案
你可以直接使用Flutter的DropdownButtonFormField组件,它原生结合了输入框样式与下拉选择功能,完全匹配你的设计需求。
改造后的代码
SizedBox( width: 400, height: 64, child: DropdownButtonFormField<String>( hint: const Text('Category Food'), decoration: InputDecoration( border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), ), // 自定义下拉选项,可根据需求修改 items: const [ DropdownMenuItem(value: 'food', child: Text('Food')), DropdownMenuItem(value: 'snack', child: Text('Snack')), DropdownMenuItem(value: 'beverage', child: Text('Beverage')), ], onChanged: (selectedValue) { // 这里处理选中值的逻辑 print('选中分类:$selectedValue'); }, // 可选:自定义下拉箭头样式 icon: const Icon(Icons.arrow_drop_down), ), )
核心说明
- 保留了你原有的
SizedBox尺寸和InputDecoration圆角边框配置,样式完全对齐 hint替代原TextField的hintText,未选择时显示提示文本items定义下拉选项集合,每个选项包含实际值和显示文本onChanged回调接收选中的值,可在此实现业务逻辑
内容的提问来源于stack exchange,提问作者Bilbo Baggins
相关产品推荐
相关产品推荐

