如何为Flutter SegmentedButton设置选中与未选分段的不同颜色
要实现SegmentedButton的分段在选中和未选中时显示不同颜色,核心思路是根据当前选中状态动态切换每个分段的背景色与文本色,以下是具体实现方案:
实现步骤
- 维护一个记录选中分段状态的集合(即使关闭多选,SegmentedButton的
selected参数也要求传入集合类型) - 在每个
ButtonSegment的label中,通过判断当前分段的value是否在选中集合里,分别设置容器的背景色和文本颜色 - 通过
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
相关产品推荐
相关产品推荐

