如何在Flutter中更改TextButton的背景颜色?

58

我正在尝试将我的FlatButton迁移到TextButton。由于升级了我的Flutter版本,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。然而Dart会说:

参数类型'MaterialColor'不能赋值给参数类型'MaterialStateProperty<Color>'。

我该如何像以前在FlatButton中一样使用红色来样式化我的TextButton?我需要创建一个带有红色的MaterialStateProperty<Color>吗?

4个回答

106

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

因此,您需要使用MaterialStateProperty类来应用颜色。以下是一个快速示例:

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

2022更新

从版本3.0.1开始,我们可以使用MaterialStatePropertyAll作为const。因此,更好的方法是使用它:

TextButton(
    child: Text('test'),
    style: const ButtonStyle(
        backgroundColor: MaterialStatePropertyAll(Colors.red),
    ),
    onPressed: () {},
),

3
我可以问一下为什么我必须使用 MaterialStateProperty.all 吗?为什么不能直接使用 Colors.red - LOLWTFasdasd asdad
4
根据文档所述,bacgroundColor不是Color类型,因此您无法使用Colors.red。 您可以在Flutter文档中找到有关MaterialStateProperty的更多详细信息:https://api.flutter.dev/flutter/material/MaterialStateProperty-class.html。 - Jouby

36

如果您正在寻找更清晰、更简单的方法来完成此操作,可以使用 TextButton.styleFrom()。示例:

TextButton(
  child: Text('Example'),
  onPressed: () {},
  style: TextButton.styleFrom(backgroundColor: Colors.red),
)

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


3

可以尝试这种方式:

TextButton(
  onPressed: () {},
  child: Container(
    padding: EdgeInsets.fromLTRB(30, 10, 30, 10),
    color: Colors.red,
    child: Text(""),
  ),
)

1
最简单的方法是为添加背景颜色
TextButton(
    style: TextButton.styleFrom(backgroundColor: Colors.red),
),

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接