Flutter中DropdownButton与DropdownMenu边框及样式定制问题
解决方案
1. 给下拉菜单添加边框
在DropdownButton中通过menuStyle属性设置下拉菜单的边框,和按钮的边框样式保持统一:
menuStyle: MenuStyle( shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(7), side: const BorderSide(width: 1, color: Color(0xFF00AFEF)), ), ), ),
2. 正确设置选项高度
不要在DropdownMenuItem的子容器里设置高度,直接使用DropdownMenuItem自带的itemHeight参数,避免布局冲突:
DropdownMenuItem( itemHeight: 21.h, // 对应需求的21px高度(使用screenutil则保留.h) // ...其他属性 )
3. 实现悬停/选中的背景色效果
- 选中状态:通过
DropdownMenuItem的selectedBackgroundColor参数设置选中时的背景色 - 鼠标悬停:在子组件外层包裹
MouseRegion,监听悬停事件并更新状态,动态切换背景色
完整修改后的代码
// 在State类中新增变量 String? hoveredOption; var genderList = [ 'Female', 'Male', 'Other', ]; String? selection; final border = const OutlineInputBorder( borderSide: BorderSide( width: 1, color: Color(0xFF00AFEF), ), borderRadius: BorderRadius.all(Radius.circular(7)), ); // ...其他代码 SizedBox( height: 38.h, child: InputDecorator( decoration: InputDecoration( contentPadding: EdgeInsets.zero, border: border, enabledBorder: border, ), child: DropdownButtonHideUnderline( child: DropdownButton<String>( isExpanded: true, hint: Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.symmetric(horizontal: 13.w), child: const Text( 'Gender', style: TextStyle( fontSize: 14, color: Color(0xFF606060), ), ), ), ), value: selection, icon: Container( margin: EdgeInsets.symmetric(horizontal: 13.w), height: 10.r, width: 16.r, alignment: Alignment.center, child: SvgPicture.asset(AppIcons.arrowDown), ), onChanged: (String? val) { setState(() => selection = val); }, // 设置下拉菜单边框 menuStyle: MenuStyle( shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(7), side: const BorderSide(width: 1, color: Color(0xFF00AFEF)), ), ), ), items: genderList.map((option) { final isSelected = selection == option; return DropdownMenuItem<String>( itemHeight: 21.h, value: option, selectedBackgroundColor: const Color(0xFFCBF1FF), child: MouseRegion( onHover: (_) { setState(() => hoveredOption = option); }, onExit: (_) { setState(() => hoveredOption = null); }, child: Container( width: double.infinity, alignment: Alignment.centerLeft, padding: EdgeInsets.symmetric(horizontal: 13.w), color: isSelected ? const Color(0xFFCBF1FF) : hoveredOption == option ? const Color(0xFFE6F7FF) // 悬停背景色可按需调整 : Colors.transparent, child: Text( option, style: const TextStyle( fontSize: 12, color: Color(0xFF606060), ), ), ), ), ); }).toList(), selectedItemBuilder: (con) { return genderList.map((val) { return Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.only(left: 13.w), child: Text( val, style: const TextStyle( fontSize: 14, color: Color(0xFF606060), ), ), ), ); }).toList(); }, ), ), ), );
内容的提问来源于stack exchange,提问作者Shubham
相关产品推荐
相关产品推荐

