0

我已经迁移到 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时,它给了我错误。

所以我想知道ButtonsFlutter 2.0 中的行为如何以及我们如何style做到Buttons

我的代码片段在这里,我想在其中设置按钮样式。

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),
                    ),
4

2 回答 2

0

style带有 a的参数backgroundcolor是执行此操作的方法,但不接受Color对象,它的类型是MaterialStateProperty<Color?>?,因此您应该提供该类型的对象。

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

于 2021-03-24T15:40:06.870 回答
0

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

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

    ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.green),

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

    ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith( (Set states) { if (states.contains(MaterialState.pressed)) return Theme.of(context).colorScheme.primary.withOpacity(0.5); return null; // 使用组件的默认值. }, ), ),

于 2021-04-03T05:23:11.263 回答