如何在颤动中更改文本按钮的背景颜色?

LOL*_*dad 21 flutter

我正在尝试将我的迁移FlatButtonTextButton. 自从FlatButtons我升级我的颤振版本以来已被弃用。我目前正在努力调整背景颜色。

旧按钮:

FlatButton(
        height: height,
        onPressed: onPressed,
        shape: baseButtonBorder,
        color: Colors.red,
        child: Text(label, style: TextStyle(color: fontColor, fontWeight: boldLabel ? FontWeight.bold : FontWeight.normal)),
      )`
Run Code Online (Sandbox Code Playgroud)

新按钮:

TextButton(
        onPressed: onPressed,
        style: ButtonStyle(backgroundColor: Colors.red), // <-- Does not work
        child: Text(label, style: TextStyle(color: fontColor, fontWeight: boldLabel ? FontWeight.bold : FontWeight.normal)),
      ),
Run Code Online (Sandbox Code Playgroud)

平面按钮没有color属性,所以我尝试使用该style属性并添加一个ButtonStyle. 如何飞镖 说:

The argument type 'MaterialColor' can't be assigned to the parameter type 'MaterialStateProperty<Color>'.

我怎样才能TextButton像以前那样用红色来设计我的风格FlatButton?我需要MaterialStateProperty<Color>用红色创建一个吗?

Jou*_*uby 39

backgroundColor属性是MaterialStateProperty<Color?>类型。您可以查看 Flutter 文档

所以你必须使用MaterialStateProperty类来应用颜色。一个简单的例子:

TextButton(
    child: Text('test'),
    style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.red)),
    onPressed: () {},
),
Run Code Online (Sandbox Code Playgroud)

  • 正如文档所述,“bacgroundColor”不是“Color”类型,因此您不能使用“Colors.red”。您可以在 Flutter 文档中找到有关“MaterialStateProperty”的更多详细信息:https://api.flutter.dev/flutter/material/MaterialStateProperty-class.html (4认同)
  • 请问为什么我必须使用 `MaterialStateProperty.all` ?为什么我不能直接使用`Colors.red`? (3认同)

小智 14

对于正在寻找更清晰、更简单的方法来执行此操作的人,您可以使用TextButton.styleFrom(). 例子:

TextButton(
  child: Text('Example'),
  onPressed: () {},
  style: TextButton.styleFrom(backgroundColor: Colors.red),
)
Run Code Online (Sandbox Code Playgroud)

您可以在 styleFrom 中自定义几乎任何您想要的东西。这也适用于其他按钮,例如ElevatedButtonOutlinedButton