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

Flutter中如何修改Material库YearPicker的选中颜色?

修改Flutter YearPicker选中颜色为绿色的方法

YearPicker的选中样式由Material主题控制,你可以通过用Theme组件包裹YearPicker的方式,自定义局部主题来修改选中颜色,具体实现如下:

直接在原有代码基础上,给YearPicker套一层Theme,在ThemeData里修改colorScheme的primary(选中背景色)和onPrimary(选中文字色)参数即可:

return AlertDialog(
  title: const Text("Select Year"),
  content: SizedBox(
    width: 300,
    height: 300,
    child: Theme(
      data: Theme.of(context).copyWith(
        colorScheme: Theme.of(context).colorScheme.copyWith(
          primary: Colors.green, // 选中年份的背景色
          onPrimary: Colors.white, // 选中年份的文字颜色
        ),
      ),
      child: YearPicker(
        firstDate: DateTime(DateTime.now().year - 23, 1),
        lastDate: DateTime(DateTime.now().year),
        initialDate: DateTime.now(),
        selectedDate: selectedDate,
        onChanged: (DateTime dateTime) {
          Navigator.pop(context);
        },
      ),
    ),
  ),
);

如果想使用预设的绿色色系,也可以用ColorScheme.fromSwatch的方式:

data: Theme.of(context).copyWith(
  colorScheme: ColorScheme.fromSwatch(
    primarySwatch: Colors.green,
  ).copyWith(
    onPrimary: Colors.white,
  ),
),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 02:12:12