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

Flutter中如何为SegmentedButton选中项添加阴影轮廓?

解决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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 08:15:07