【问题标题】:How can I change the background color of a textbutton in flutter?如何在颤动中更改文本按钮的背景颜色?
【发布时间】:2021-06-07 08:45:00
【问题描述】:

我正在尝试将我的 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&lt;Color&gt;'.

如何像以前使用FlatButton 一样将TextButton 设置为红色?我需要用红色创建MaterialStateProperty&lt;Color&gt;吗?

【问题讨论】:

    标签: flutter


    【解决方案1】:

    backgroundColor 属性是MaterialStateProperty&lt;Color?&gt; 类型。你可以签到Flutter documentation

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

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

    【讨论】:

    • 请问为什么我必须使用MaterialStateProperty.all ?为什么我不能直接使用Colors.red
    • 如文档所述,bacgroundColor 不是Colortype,因此您不能使用Colors.red。您可以在 Flutter 文档中找到有关 MaterialStateProperty的更多详细信息:api.flutter.dev/flutter/material/…
    【解决方案2】:

    对于寻求更清晰、更轻松的方法的人,您可以使用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(""),
      ),
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-25
      • 2021-12-14
      • 2020-11-07
      • 1970-01-01
      • 2014-12-26
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多