[英]How can I change the background color of a textbutton in flutter?
I'm trying to migrate my FlatButton
to TextButton
.我正在尝试将我的
FlatButton
迁移到TextButton
。 Since FlatButtons
are deprecated since I upgraded my flutter version.因为自从我升级了 flutter 版本后,
FlatButtons
已被弃用。 I'm currently struggling with adapting the background color.我目前正在努力调整背景颜色。
Old button:旧按钮:
FlatButton(
height: height,
onPressed: onPressed,
shape: baseButtonBorder,
color: Colors.red,
child: Text(label, style: TextStyle(color: fontColor, fontWeight: boldLabel ? FontWeight.bold : FontWeight.normal)),
)`
New Button:新按钮:
TextButton(
onPressed: onPressed,
style: ButtonStyle(backgroundColor: Colors.red), // <-- Does not work
child: Text(label, style: TextStyle(color: fontColor, fontWeight: boldLabel ? FontWeight.bold : FontWeight.normal)),
),
The flat button does not have a color
attribute so I tried to use the style
attribute and add a ButtonStyle
.平面按钮没有
color
属性,所以我尝试使用style
属性并添加一个ButtonStyle
。 How ever dart says: dart 说:
The argument type 'MaterialColor' can't be assigned to the parameter type 'MaterialStateProperty<Color>'.
How can I style my TextButton
with the color red like I used to do with my FlatButton
?如何像以前对 FlatButton 所做的那样使用红色设置
TextButton
的FlatButton
? Do I need to create a MaterialStateProperty<Color>
with red?我需要用红色创建
MaterialStateProperty<Color>
吗?
backgroundColor
property is MaterialStateProperty<Color?>
type. backgroundColor
属性是MaterialStateProperty<Color?>
类型。 You can check in Flutter documentation .您可以查看Flutter 文档。
So you have to use MaterialStateProperty
class to apply color.所以你必须使用
MaterialStateProperty
class 来应用颜色。 A quick example:一个简单的例子:
TextButton(
child: Text('test'),
style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.red)),
onPressed: () {},
),
For people looking for a clearer and easier way to do this, you can use TextButton.styleFrom()
.对于寻找更清晰、更简单的方法的人,您可以使用
TextButton.styleFrom()
。 Example:例子:
TextButton(
child: Text('Example'),
onPressed: () {},
style: TextButton.styleFrom(backgroundColor: Colors.red),
)
You can customize almost anything you want in styleFrom.您可以在 styleFrom 中自定义几乎任何您想要的东西。 This works for other buttons too, like
ElevatedButton
and OutlinedButton
.这也适用于其他按钮,例如
ElevatedButton
和OutlinedButton
。
Try this way,试试这个方法
TextButton(
onPressed: () {},
child: Container(
padding: EdgeInsets.fromLTRB(30, 10, 30, 10),
color: Colors.red,
child: Text(""),
),
)
most Easy Way to add a BackGroundColor to Textbutton
向
Textbutton
添加背景颜色的最简单方法
TextButton(
style: TextButton.styleFrom(backgroundColor: Colors.red),
),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.