Flutter 中的 ButtonStyle 和 MaterialStateProperty 是在 Flutter 2.0 发布时引入的。在 Flutter 1 中,我们可以通过设置 textColor、backgroundColor 等参数来快速配置按钮的样式。但是在 Flutter 2 中,这些参数被废弃了,取而代之的是 ButtonStyle。ButtonStyle 可以通过 MaterialStateProperty 来支持不同平台下的交互状态展示。本文将深入探讨这两个新特性。
1.MaterialStateProperty
MaterialStateProperty 的设计理念基于 Material Design 去针对全平台的交互进行兼容。在 MaterialStateProperty 体系中,有一个 MaterialState 枚举,它包含了多种不同的状态,例如 disabled、hovered、focused、selected、pressed、dragged、error 等。MaterialStateProperty 可以通过这些状态来控制控件的样式。
举个例子,假设我们需要在按钮悬停时修改按钮的背景颜色。在Flutter 1 中,我们可以这样写:
FlatButton(
onPressed: () {},
color: Colors.blue,
hoverColor: Colors.green,
child: Text('Button'),
)
但是在Flutter 2 中,我们需要使用 ButtonStyle 和 MaterialStateProperty 来实现相同的效果。代码如下:
TextButton(
onPressed: () {},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.hovered)) {
return Colors.green;
}
return Colors.blue;
}),
),
child: Text('Button'),
)
在上述代码中,我们使用MaterialStateProperty.resolveWith 方法来处理按钮的背景颜色,这样就可以轻松地实现不同状态下的样式切换。在这个例子中,我们使用 MaterialState.hovered 来处理按钮悬停时的样式。
需要注意的是,MaterialStateProperty 不仅适用于按钮,还适用于其他控件,例如 Checkbox、Radio、Slider 等。
2.ButtonStyle
ButtonStyle 是 Flutter 中一种全新的样式定义方式,它用于定义控件的样式。ButtonStyle 的设计目的是为了在不同平台下提供一致的外观和行为。例如,当用户在不同的操作系统上运行应用程序时,ButtonStyle 可以确保按钮的样式和行为都是一致的。