You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改DropdownButtonFormField中选中DropdownMenuItem的背景色

修改DropdownButtonFormField选中项背景色的解决方案

方法1:通过selectedItemBuilder自定义选中项样式

直接在DropdownButtonFormField中配置selectedItemBuilder,自定义选中状态下的组件外观,包括背景色:

DropdownButtonFormField<String>(
  value: selectedValue,
  selectedItemBuilder: (BuildContext context) {
    return items.map((String item) {
      return Container(
        color: Colors.blue[100], // 设置选中项的背景色
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Text(item),
      );
    }).toList();
  },
  items: items.map((String item) {
    return DropdownMenuItem<String>(
      value: item,
      child: Text(item),
    );
  }).toList(),
  onChanged: (String? newValue) {
    setState(() {
      selectedValue = newValue!;
    });
  },
)

方法2:在DropdownMenuItem中根据选中状态动态设置背景色

通过判断当前项是否为选中值,动态给DropdownMenuItem的子元素添加背景容器:

DropdownButtonFormField<String>(
  value: selectedValue,
  items: items.map((String item) {
    return DropdownMenuItem<String>(
      value: item,
      child: Container(
        color: selectedValue == item ? Colors.green[100] : null, // 选中时的背景色
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: Text(item),
      ),
    );
  }).toList(),
  onChanged: (String? newValue) {
    setState(() {
      selectedValue = newValue!;
    });
  },
)

方法3:通过主题修改全局默认样式

如果需要全局统一修改,可以在ThemeData中配置相关属性:

Theme(
  data: Theme.of(context).copyWith(
    dropdownMenuTheme: DropdownMenuThemeData(
      menuStyle: MenuStyle(
        selectedBackgroundColor: MaterialStateProperty.all(Colors.orange[100]), // 选中项背景色
      ),
    ),
  ),
  child: DropdownButtonFormField<String>(
    value: selectedValue,
    items: items.map((String item) => DropdownMenuItem(value: item, child: Text(item))).toList(),
    onChanged: (val) => setState(() => selectedValue = val!),
  ),
)

注意:不同Flutter版本的主题属性可能略有差异,若上述属性不生效,可以尝试调整highlightColor等相关主题参数。

内容的提问来源于stack exchange,提问作者Alex Krasnov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:15:09