Flutter中如何为SegmentedButton选中项添加阴影轮廓?
要实现选中项带阴影、未选中项为黄色的效果,你之前的写法核心问题是全局设置的elevation不会单独作用于选中项,且SegmentedButton默认合并相邻按钮边框,需要单独给选中状态配置样式。
完整实现代码
首先定义枚举(对应你的Calendar类型):
enum Calendar { day, week }
在State类中管理选中状态:
Calendar? selectedCalendar = Calendar.day;
最终的SegmentedButton实现:
SegmentedButton<Calendar>( selected: {selectedCalendar}, onSelectionChanged: (newSelection) { setState(() { selectedCalendar = newSelection.first; }); }, // 未选中项的全局样式 style: SegmentedButton.styleFrom( backgroundColor: Colors.yellow[200], // 未选中设为黄色 foregroundColor: Colors.grey, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8)), ), ), // 单独配置选中项的样式(关键) selectedStyle: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.white), foregroundColor: MaterialStateProperty.all(Colors.black), elevation: MaterialStateProperty.all(4), // 选中项的阴影高度 shadowColor: MaterialStateProperty.all(Colors.grey.shade400), // 阴影颜色 shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), ), ), segments: const [ ButtonSegment<Calendar>( value: Calendar.day, label: Text('Day'), ), ButtonSegment<Calendar>( value: Calendar.week, label: Text('Week'), ), ], )
关键说明
selectedStyle:专门为选中项设置独立样式,这里单独指定elevation和shadowColor是让选中项显示阴影的核心(全局的elevation会被选中状态的默认值覆盖)。- 未选中项的黄色背景直接在
styleFrom中配置,无需额外逻辑。 - 若阴影被父容器裁切,可给SegmentedButton外层加
Padding(padding: EdgeInsets.all(8), child: ...),给阴影留出显示空间。
内容的提问来源于stack exchange,提问作者Muhammad Taimoor
相关产品推荐
相关产品推荐

