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

如何为Flutter SegmentedButton设置选中与未选分段的不同颜色

为Flutter SegmentedButton设置选中/未选中状态的自定义样式

要实现SegmentedButton的分段在选中和未选中时显示不同颜色,核心思路是根据当前选中状态动态切换每个分段的背景色与文本色,以下是具体实现方案:

实现步骤

  1. 维护一个记录选中分段状态的集合(即使关闭多选,SegmentedButton的selected参数也要求传入集合类型)
  2. 在每个ButtonSegment的label中,通过判断当前分段的value是否在选中集合里,分别设置容器的背景色和文本颜色
  3. 通过onSelectionChanged回调更新选中状态,触发UI重建

完整代码示例

SegmentedButton<String>(
  selected: _selectedSegment,
  showSelectedIcon: false,
  multiSelectionEnabled: false, // 关闭多选,确保每次只能选中一个分段
  segments: [
    ButtonSegment(
      value: 'pending',
      label: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          // 根据选中状态切换背景色
          color: _selectedSegment.contains('pending') 
              ? const Color(0xff124549) 
              : Colors.grey[200],
        ),
        child: Text(
          'Pending',
          style: TextStyle(
            // 根据选中状态切换文本颜色
            color: _selectedSegment.contains('pending') 
                ? Colors.white 
                : const Color(0xff124549),
          ),
        ),
      ),
    ),
    ButtonSegment(
      value: 'accepted',
      label: Container(
        padding: const EdgeInsets.all(12), // 统一padding,保持样式一致
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          color: _selectedSegment.contains('accepted') 
              ? const Color(0xff124549) 
              : Colors.grey[200],
        ),
        child: Text(
          'Accepted',
          style: TextStyle(
            color: _selectedSegment.contains('accepted') 
                ? Colors.white 
                : const Color(0xff124549),
          ),
        ),
      ),
    ),
  ],
  onSelectionChanged: (newSelection) {
    setState(() {
      _selectedSegment = newSelection;
    });
  },
)

优化建议

  • 把重复使用的颜色提取为常量,比如:
    const _selectedBgColor = Color(0xff124549);
    const _selectedTextColor = Colors.white;
    const _unselectedBgColor = Colors.grey[200];
    const _unselectedTextColor = Color(0xff124549);
    
    这样修改样式时只需改动一处,更易维护
  • 如果需要多个页面复用类似样式,可以封装一个自定义的CustomButtonSegment组件,减少重复代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:27:29