如何在颤动中更改文本按钮的背景颜色?
我正在尝试将我的迁移FlatButton到TextButton. 自从FlatButtons我升级我的颤振版本以来已被弃用。我目前正在努力调整背景颜色。
旧按钮:
FlatButton(
height: height,
onPressed: onPressed,
shape: baseButtonBorder,
color: Colors.red,
child: Text(label, style: TextStyle(color: fontColor, fontWeight: boldLabel ? FontWeight.bold : FontWeight.normal)),
)`
新按钮:
TextButton(
onPressed: onPressed,
style: ButtonStyle(backgroundColor: Colors.red), // <-- Does not work
child: Text(label, style: TextStyle(color: fontColor, fontWeight: boldLabel ? FontWeight.bold : FontWeight.normal)),
),
平面按钮没有color属性,所以我尝试使用该style属性并添加一个ButtonStyle. 如何飞镖 说:
The argument type 'MaterialColor' can't be assigned to the parameter type 'MaterialStateProperty<Color>'.
我怎样才能TextButton像以前那样用红色来设计我的风格FlatButton?我需要MaterialStateProperty<Color>用红色创建一个吗?
回答
backgroundColor属性是MaterialStateProperty<Color?>类型。您可以查看 Flutter 文档。
所以你必须使用MaterialStateProperty类来应用颜色。一个简单的例子:
TextButton(
child: Text('test'),
style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.red)),
onPressed: () {},
),
- As documentation says, `bacgroundColor` isn't `Color`type, so you can't use `Colors.red`. You can find more details about `MaterialStateProperty`in Flutter documentation: https://api.flutter.dev/flutter/material/MaterialStateProperty-class.html
- May I ask why I have to use `MaterialStateProperty.all` ? Why can't 'I use `Colors.red` directly?
回答
对于正在寻找更清晰、更简单的方法来执行此操作的人,您可以使用TextButton.styleFrom(). 例子:
TextButton(
child: Text('Example'),
onPressed: () {},
style: TextButton.styleFrom(backgroundColor: Colors.red),
)
您可以在 styleFrom 中自定义几乎任何您想要的东西。这也适用于其他按钮,例如ElevatedButton和OutlinedButton。