问题描述
我已经迁移到 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
?
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),),
解决方法
带有 style
的 backgroundcolor
参数是这样做的方法,但不接受 Color
对象,它的类型是 MaterialStateProperty<Color?>?
所以你应该提供一个对象那种类型。
文档在这里https://api.flutter.dev/flutter/material/TextButton-class.html
在这里https://api.flutter.dev/flutter/material/ButtonStyle-class.html
按钮现在有一个状态,所以你必须为每个状态定义颜色:
-
您可以为所有状态定义一种颜色。
按钮样式( backgroundColor: MaterialStateProperty.all(Colors.green),
-
您可以为每个状态定义不同的颜色。
按钮样式( backgroundColor: MaterialStateProperty.resolveWith( (设置状态){ 如果(states.contains(MaterialState.pressed)) 返回 Theme.of(context).colorScheme.primary.withOpacity(0.5); 返回空; // 使用组件的默认值。 },),