我正在尝试将我的 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>
吗?
答案 0 :(得分:25)
backgroundColor
属性是 MaterialStateProperty<Color?>
类型。您可以在Flutter documentation登记。
所以你必须使用 MaterialStateProperty
类来应用颜色。一个简单的例子:
TextButton(
child: Text('test'),
style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.red)),
onPressed: () {},
),
答案 1 :(得分:4)
对于寻求更清晰、更简单的方法来执行此操作的人,您可以使用 TextButton.styleFrom()
。示例:
TextButton(
child: Text('Example'),
onPressed: () {},
style: TextButton.styleFrom(backgroundcolor: Colors.red),
)
您几乎可以在 styleFrom 中自定义任何您想要的内容。这也适用于其他按钮,例如 ElevatedButton
和 OutlinedButton
。
答案 2 :(得分:1)
试试这个方法,
TextButton(
onPressed: () {},
child: Container(
padding: EdgeInsets.fromLTRB(30, 10, 30, 10),
color: Colors.red,
child: Text(""),
),
)