使用 ButtonStyle 更改 Flutter 中 ElevatedButton 的文本颜色

Change the text color of an ElevatedButton in Flutter with ButtonStyle

我想要一个按钮:

我正在尝试使用 ButtonStyle 实现此目的 class。

ElevatedButton(
  child: Text("Example"),
  onPressed: onPressed, // onPressed is a function
  style: ButtonStyle(
    backgroundColor: MaterialStateProperty.resolveWith((states) {
      if (states.contains(MaterialState.disabled)) { return KPColors.offWhite; }
      if (states.contains(MaterialState.pressed)) { return KPColors.primaryLight; }
      return KPColors.primaryExtraLight;
    }),
    textStyle: MaterialStateProperty.resolveWith((states) {
      Color textColor = states.contains(MaterialState.disabled) ? KPColors.gray : KPColors.primary;
      return TextStyle(fontSize: 18, color: textColor);
    }),
    overlayColor: MaterialStateProperty.all(KPColors.clear), // prevents the shimmer effect when pressing the button
    shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(16))), // Rounds the corners
    elevation: MaterialStateProperty.all(0), // Prevents shadow around button
  ),
),

代码成功更改了按钮的背景颜色,但没有更改文本颜色,文本颜色显示为白色而不是我的自定义颜色。我认为这是因为 ElevatedButton 的 child 是一个文本小部件,它具有覆盖我的默认文本颜色。

我该如何解决这个问题?我已经知道我可以通过使用 ElevatedButton.styleFrom(...) 并设置 onPrimary 属性 而不是 ButtonStyle 来更改按钮的文本颜色,但这会使具有不同的按钮变得更加困难颜色取决于按钮的按下和禁用状态。

您需要在 ButtonStyle

中设置 foregroundColor

例如:

foregroundColor: MaterialStateProperty.resolveWith((states) {
      if (states.contains(MaterialState.disabled)) { return Colors.grey; }
      if (states.contains(MaterialState.pressed)) { return Colors.green; }
      return Colors.blue;
    })

你可以使用ElevatedButton.styleFrom

ElevatedButton(
  child: Text("Example",style:TextStyle(color:isActive ? Colors.white : Colors.black)),
  onPressed: isActive ? (){print('do somthing');} : (){}, // onPressed is a function
  style: ElevatedButton.styleFrom(primary: isActive ? Colors.blue : Colors.grey),
        )