Flutter中如何实现Dropdown下拉菜单选中项高亮效果
Flutter Dropdown下拉菜单选中项高亮实现方案
核心逻辑为对比每个下拉项的value与当前全局选中值,匹配时自定义高亮样式即可,具体实现步骤如下:
- 第一步:定义状态变量与选项列表
首先在State类中定义存储选中值的变量和下拉选项数据源:
// 存储当前选中的下拉值 String? selectedValue; // 下拉选项数据源 final List<String> optionList = ['选项A', '选项B', '选项C', '选项D'];
- 第二步:自定义下拉项组件实现高亮
构建DropdownMenuItem时判断当前项是否为选中状态,对应设置背景色、文字样式等高亮效果:
DropdownButton<String>( value: selectedValue, hint: const Text('请选择选项'), isExpanded: true, items: optionList.map((currentOption) { // 判断当前选项是否为已选中项 final bool isSelected = currentOption == selectedValue; return DropdownMenuItem<String>( value: currentOption, child: Container( width: double.infinity, padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12), // 选中项添加高亮背景 decoration: isSelected ? BoxDecoration( color: Colors.lightBlueAccent.shade100, borderRadius: BorderRadius.circular(4), ) : null, child: Text( currentOption, style: TextStyle( // 选中项文字高亮 color: isSelected ? Colors.blueAccent : Colors.black87, fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal, ), ), ), ); }).toList(), onChanged: (newValue) { // 更新选中状态触发UI重绘 setState(() { selectedValue = newValue; }); }, )
- 可选配置:下拉框闭合后选中项样式自定义
如果需要闭合状态下的选中项也展示特殊样式,可以搭配selectedItemBuilder属性实现:
DropdownButton<String>( // 省略上述其他配置属性 selectedItemBuilder: (BuildContext context) { return optionList.map((option) { return Align( alignment: Alignment.centerLeft, child: Text( option, style: const TextStyle( color: Colors.blueAccent, fontWeight: FontWeight.w600, ), ), ); }).toList(); }, )
如果你使用的是Flutter 3.10及以上版本推出的新版
DropdownMenu组件,实现逻辑完全一致,只需要在构建DropdownMenuEntry时判断选中状态,对应设置entry的样式属性即可。
内容的提问来源于stack exchange,提问作者Anoop Thiruonam
相关产品推荐
相关产品推荐

