如何修改DropdownButtonFormField下拉列表选中项的文字颜色
Flutter 下拉组件选中态与菜单文本颜色分离实现
问题原因
当前代码中DropdownButtonFormField的style属性会同时生效于两个场景:组件闭合时输入框位置的选中项文本、下拉展开后的所有菜单选项文本,因此直接设置为黑色会导致两处文本全为黑色。另外你在onChanged回调中写的TextStyle(color: Colors.white);属于无效代码,没有绑定到任何组件属性,不会产生任何效果。
实现步骤
- 删除
onChanged回调中无意义的孤立TextStyle代码 - 两种实现方案二选一即可:
- 方案1(简单直接):将组件根
style设为白色控制选中态文本,给每个DropdownMenuItem内部的Text单独设置黑色样式,保证下拉菜单内文本在白色背景下清晰可见 - 方案2(代码更简洁):保留根
style为黑色作为菜单选项默认样式,通过selectedItemBuilder参数单独构建选中后展示的白色文本组件,无需逐个修改菜单项样式
- 方案1(简单直接):将组件根
完整修正代码(方案1)
child: DropdownButtonFormField( // 控制组件闭合时选中项文本为白色 style: TextStyle(color: Colors.white), decoration: InputDecoration( focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.cyan, width: 1.0), borderRadius: BorderRadius.circular(10), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.white, width: 1.0), borderRadius: BorderRadius.circular(10), ), hintText: 'Year of Education', hintStyle: TextStyle( color: Color.fromARGB(255, 245, 244, 255), fontStyle: FontStyle.italic, fontSize: 10, ), ), value: dropdownValue, items: const [ // 每个菜单项单独设置黑色文本 DropdownMenuItem<String>( child: Text('-choose-', style: TextStyle(color: Colors.black)), value: ''), DropdownMenuItem<String>( child: Text('First', style: TextStyle(color: Colors.black)), value: 'First'), DropdownMenuItem<String>( child: Text('Second', style: TextStyle(color: Colors.black)), value: 'Second'), DropdownMenuItem<String>( child: Text('Third', style: TextStyle(color: Colors.black)), value: 'Third'), DropdownMenuItem<String>( child: Text('Fourth', style: TextStyle(color: Colors.black)), value: 'Fourth'), DropdownMenuItem<String>( child: Text('Fifth', style: TextStyle(color: Colors.black)), value: 'Fifth'), ], onChanged: (String? value) { setState(() { dropdownValue = value!; }); }, validator: (value) { if (dropdownValue == '') return 'You must select a value.'; return null; } ),
优化方案核心代码(方案2)
child: DropdownButtonFormField( // 下拉菜单选项默认使用黑色文本 style: TextStyle(color: Colors.black), // 单独构建选中后在输入框位置展示的组件,设置白色文本 selectedItemBuilder: (BuildContext context) { return ['', 'First', 'Second', 'Third', 'Fourth', 'Fifth'].map((String val) { return Text( val == '' ? '-choose-' : val, style: TextStyle(color: Colors.white), ); }).toList(); }, // 其余decoration、items、onChanged、validator属性和原代码一致,无需修改菜单项样式 // ... )
效果展示


内容的提问来源于stack exchange,提问作者mentos
相关产品推荐
相关产品推荐

