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

如何修改Flutter中ElevatedButton选中状态下的文本颜色

问题原因

你当前代码中ElevatedButton.styleFrom里的onPrimary属性是固定写死的Colors.black,该属性专门用于控制按钮的文本、图标等前景色,所以选中状态下文本颜色不会跟随背景变化。

解决方法

把每个按钮的onPrimary参数改为动态判断值即可,以第一个按钮(索引0)为例:
原代码对应部分:

style: ElevatedButton.styleFrom(
    side: BorderSide(width: 2.5, color: Colors.grey),
    primary: index == 0 ? Colors.red : Colors.white,
    onPrimary: Colors.black, // 固定值导致文本颜色不变
    textStyle: const TextStyle(
      fontSize: 15,
    )),

修改后:

style: ElevatedButton.styleFrom(
    side: BorderSide(width: 2.5, color: Colors.grey),
    primary: index == 0 ? Colors.red : Colors.white,
    onPrimary: index == 0 ? Colors.white : Colors.black, // 动态匹配选中状态
    textStyle: const TextStyle(
      fontSize: 15,
    )),

剩下索引为1、2的两个按钮,对应把判断条件改为index == 1、index == 2即可生效。

可选优化(减少冗余代码)

你可以把班级名称存为列表,用循环批量生成按钮,避免重复编写相似的按钮代码:

// 先定义班级列表
final List<String> classList = ['Clas 01', 'Clas 02', 'Clas 03'];

// 在ListView的children中替换原来的三个按钮代码
...classList.asMap().entries.map((entry) {
  int btnIndex = entry.key;
  String className = entry.value;
  return Container(
    margin: const EdgeInsets.fromLTRB(75, 0, 75, 10),
    height: 60.0,
    child: ElevatedButton(
      onPressed: () {
        setState(() {
          index = btnIndex;
        });
      },
      child: SizedBox(
        width: double.infinity,
        child: Text(
          className,
          textAlign: TextAlign.left,
        ),
      ),
      style: ElevatedButton.styleFrom(
        side: const BorderSide(width: 2.5, color: Colors.grey),
        primary: index == btnIndex ? Colors.red : Colors.white,
        onPrimary: index == btnIndex ? Colors.white : Colors.black,
        textStyle: const TextStyle(fontSize: 15),
      ),
    ),
  );
}).toList(),

内容的提问来源于stack exchange,提问作者Maahdi.Codes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:06:03