什么是MaterialStateProperty<Color>?
ButtonStyle 中的 MaterialStateProperty 是什么?
ThemeData(
textButtonTheme: TextButtonThemeData(
style: ButtonStyle(
backgroundColor: , //?
),
),
),
回答
我假设您想知道如何为 ButtonStyle 小部件的 backgroundColor 参数分配颜色。如果是这种情况,那么只需键入如下内容:
backgroundColor: MaterialStateProperty.all(Colors.green),
或者
backgroundColor: MaterialStateProperty.all(Color(0xFF5D5F6E)),
- This is horrible.
回答
T基于小部件的交互式“状态”解析为类型值的类的接口,该状态定义为一组 MaterialState。材料状态属性表示取决于小部件的材料“状态”的值。状态被编码为一组MaterialState值,如MaterialState.focused、MaterialState.hovered、MaterialState.pressed。例如,InkWell.overlayColor定义了在按下(“初始颜色”)、聚焦或悬停时填充墨水的颜色。InkWell 使用叠加颜色的解析方法来计算墨水池当前状态的颜色。
ButtonStyle,其用于配置的按钮等的外观TextButton,ElevatedButton和OutlinedButton, 具有许多材料状态属性。按钮小部件会跟踪它们当前的材质状态,并在需要它们的值时解析按钮样式的材质状态属性。
代码示例:
Widget build(BuildContext context) {
Color getColor(Set<MaterialState> states) {
const Set<MaterialState> interactiveStates = <MaterialState>{
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
};
if (states.any(interactiveStates.contains)) {
return Colors.blue;
}
return Colors.red;
}
return TextButton(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith(getColor),
),
onPressed: () {},
child: Text('TextButton'),
);
}
一个简单的使用方法:
MaterialStateProperty.all(Colors.green) // Whatever value you want
要获得更多信息,您可以查看flutter 团队制作的 Material state properties 的官方文档。
THE END
二维码