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

如何自定义Flutter SegmentedButton选中与未选中状态的背景色

关于Flutter SegmentedButton组件选中/未选中背景色自定义的问题

我正在试用Flutter新的SegmentedButton组件,当前使用的代码如下:

SegmentedButton<int>(
  onSelectionChanged: (i) {},
  showSelectedIcon: false,
  style: ButtonStyle(
    backgroundColor: MaterialStatePropertyAll(Theme.of(context).primaryColor),
    iconColor: MaterialStateProperty.all(Colors.white),
  ),
  segments: const <ButtonSegment<int>>[
    ButtonSegment<int>(
      value: 12,
      icon: Icon(FlutterRemix.thumb_up_fill),
      enabled: true,
    ),
    ButtonSegment<int>(
      value: 20,
      icon: Icon(FlutterRemix.thumb_down_fill),
    ),
  ],
  selected: {12},
),

这段代码呈现的分段按钮效果如图所示:
SegmentedButton效果

当我设置backgroundColor: MaterialStatePropertyAll(Theme.of(context).primaryColor)时,选中与未选中按钮的背景色会被同时设置,请问如何分别自定义这两种状态的背景色?


解决方案

要分别定义选中和未选中状态的背景色,不能使用MaterialStatePropertyAll(它会给所有状态应用同一颜色),而是通过MaterialStateProperty.resolveWith方法,根据按钮的当前状态返回对应颜色。

修改后的style部分代码示例:

style: ButtonStyle(
  backgroundColor: MaterialStateProperty.resolveWith((states) {
    // 按钮处于选中状态时返回指定颜色
    if (states.contains(MaterialState.selected)) {
      return Theme.of(context).primaryColor;
    }
    // 未选中状态返回另一种颜色
    return Colors.grey[200];
  }),
  iconColor: MaterialStateProperty.resolveWith((states) {
    // 可根据状态同步调整图标颜色
    return states.contains(MaterialState.selected) ? Colors.white : Colors.black87;
  }),
),

逻辑说明:

  • MaterialStateProperty.resolveWith的回调函数会接收当前按钮的状态集合states,包含选中、禁用、悬停等状态
  • 通过判断states中是否包含MaterialState.selected,区分选中与未选中状态,返回对应背景色
  • 你可以根据需求扩展逻辑,比如添加对MaterialState.disabled等其他状态的颜色处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:02:51