作用
部分组件,比如elevatedButton的style使用的ButtonStyle, 里面设置一些颜色字体风格之类的需要用到这个类去设置,而非直接赋予Color
实践
MaterialStateProperty
enum MaterialState {/// The state when the user drags their mouse cursor over the given widget.////// See: https://material.io/design/interaction/states.html#hover.hovered,/// The state when the user navigates with the keyboard to a given widget.////// This can also sometimes be triggered when a widget is tapped. For example,/// when a [TextField] is tapped, it becomes [focused].////// See: https://material.io/design/interaction/states.html#focus.focused,/// The state when the user is actively pressing down on the given widget.////// See: https://material.io/design/interaction/states.html#pressed.pressed,/// The state when this widget is being dragged from one place to another by/// the user.////// https://material.io/design/interaction/states.html#dragged.dragged,/// The state when this item has been selected.////// This applies to things that can be toggled (such as chips and checkboxes)/// and things that are selected from a set of options (such as tabs and radio buttons).////// See: https://material.io/design/interaction/states.html#selected.selected,/// The state when this widget disabled and can not be interacted with.////// Disabled widgets should not respond to hover, focus, press, or drag/// interactions.////// See: https://material.io/design/interaction/states.html#disabled.disabled,/// The state when the widget has entered some form of invalid state.////// See https://material.io/design/interaction/states.html#usage.error,}
下面直接实践,可以看到我默认设置了一个红色,点击状态下为黄色
elevatedButtonTheme: ElevatedButtonThemeData(style: ButtonStyle(// backgroundColor: MaterialStateProperty.all(Colors.grey),backgroundColor:MaterialStateProperty.resolveWith<Color>((states) {if (states.contains(MaterialState.pressed)) {return Colors.yellow;}return Colors.red;}),),)
Api
一共只有3个api,all,resovleAs,resolveWith
all
设置全部状态共同使用的样式
MaterialStateProperty.all<Color>(Colors.grey)
resolveWith
提供回调函数,可以通过实参states去判断不同类型下返回不同的样式,return的值为该泛型
MaterialStateProperty.resolveWith<Color>((states) {if (states.contains(MaterialState.pressed)) {return Colors.yellow;}return Colors.red;},)
resolveAs
没搞懂,网上也没看到相应的demo,忽略

