我是 Flutter 的新手。
这是我的代码,
对于 ElevatedButton,
ElevatedButton(
onPressed: () {
// Add your onPressed code here!
},
child: Text("Login"),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(
AppColors.SecondaryColor),
foregroundColor: MaterialStateProperty.all<Color>(
AppColors.PrimaryColor))),
对于轮廓按钮,OutlinedButton(
onPressed: () {
// Add your onPressed code here!
},
child: Text("Register Now"),
style: OutlinedButton.styleFrom(
side: BorderSide(width: 2, color: AppColors.SecondaryColor),
))
我的问题是为什么我必须对 OutlinedButton 使用 styleFrom 而不是 ButtonStyle?如果将 OutlinedButton.styleFrom 替换为 ButtonStyle,则会出现错误。为什么?我对 ButtonStyle 和 styleFrom 的用法很困惑。因为网上的例子有的使用ButtonStyle,有的使用styleFrom。
最佳答案
正如文档所说,ElevatedButton和 OutlinedButton支持 ButtonStyle() 和 .styleFrom()。
使用 ButtonStyle() 您必须定义所有必需的属性,使用 ButtonStyle.styleFrom() 选择默认设置值,您只需更改所需的值。
如果您知道在 OutlinedButton 中使用 ButtonStyle() 时遇到了什么错误,那么帮助您会容易得多
-------------------------------------------------- -------------------------------------------------- ------------------
更新的答案
是的,因为 ButtonStyle() 中的 side 参数需要 MaterialStateProperty 而不是 BorderSide 的值。使用此代码来查看它是如何工作的:
OutlinedButton(
onPressed: null,
child: Text('Outlined Button'),
style: ButtonStyle(
side: MaterialStateProperty.all(
BorderSide.lerp(
BorderSide(
style: BorderStyle.solid,
color: Color(0xffe4e978),
width: 10.0,
),
BorderSide(
style: BorderStyle.solid,
color: Color(0xffe4e978),
width: 10.0,
),
10.0),
),
),
),
输出:看到这个 link对此有更多的了解。
关于Flutter:ButtonStyle() 和 .styleFrom() 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64764169/