【问题标题】:Changing the color and styling of the Button in Flutter在 Flutter 中更改 Button 的颜色和样式
【发布时间】:2021-06-21 05:51:59
【问题描述】:

我已经迁移到 Flutter 2.0,这只是现在的新版本。在我的项目中,我使用了Flat Buttons,但它现在在 Flutter 2.0 中已被弃用,并弹出使用Text Button 而不是Flat Buttons 的建议。

现在问题出在Flat Buttons 中,有直接设置按钮属性的选项,例如color, padding etc.,但是当我将其替换为Text Button 时,使用此属性时出错。我检查了文档,发现有style: ButtonStyle(backgroundcolor: ____________)的属性。但是当我将Colors.blue 放在backgroundcolor 属性中时,它给了我错误。

所以我想知道 Buttons 在 Flutter 2.0 中的行为如何,以及我们如何 style Buttons

我的 sn-p 代码在这里,我想在其中设置按钮样式。

Container(
                  width: 200.0,
                  child: TextButton(
                    style: ButtonStyle(), // I want to style this.
                    onPressed: () => Navigator.pushNamed(context, SignupPage.id),
                    /*color: Colors.blue,
                    padding: const EdgeInsets.all(10.0),*/ //Commented code is deprecated in Flutter 2.0
                    child: Text(
                      'Create Account',
                      style: TextStyle(color: Colors.white, fontSize: 16.0),
                    ),

【问题讨论】:

    标签: dart flutter2.0


    【解决方案1】:

    带有backgroundcolorstyle 参数是这样做的方法,但不采用Color 对象,它的类型是MaterialStateProperty<Color?>?,因此您应该提供该类型的对象。

    文档在这里https://api.flutter.dev/flutter/material/TextButton-class.html
    在这里https://api.flutter.dev/flutter/material/ButtonStyle-class.html

    【讨论】:

      【解决方案2】:

      按钮现在有一个状态,所以你必须为每个状态定义颜色:

      • 您可以为所有状态定义一种颜色。

        按钮样式( 背景颜色:MaterialStateProperty.all(Colors.green),

      • 您可以为每个状态定义不同的颜色。

        按钮样式( 背景颜色:MaterialStateProperty.resolveWith( (设置状态){ if (states.contains(MaterialState.pressed)) 返回 Theme.of(context).colorScheme.primary.withOpacity(0.5); 返回空值; // 使用组件的默认值。 }, ), ),

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-26
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        • 2019-06-23
        相关资源
        最近更新 更多