作用

部分组件,比如elevatedButtonstyle使用的ButtonStyle, 里面设置一些颜色字体风格之类的需要用到这个类去设置,而非直接赋予Color

主要是区分组件不同状态下的样式

实践

MaterialStateProperty主要是对ui组件不同的状态做区分,以 MaterialStateProperty.resolveWith为例,它提供了一个函数,类型为resolveWith(T Function(Set) ,参数类型属于Set,可以打开MaterialState源码看下有哪些状态

  1. enum MaterialState {
  2. /// The state when the user drags their mouse cursor over the given widget.
  3. ///
  4. /// See: https://material.io/design/interaction/states.html#hover.
  5. hovered,
  6. /// The state when the user navigates with the keyboard to a given widget.
  7. ///
  8. /// This can also sometimes be triggered when a widget is tapped. For example,
  9. /// when a [TextField] is tapped, it becomes [focused].
  10. ///
  11. /// See: https://material.io/design/interaction/states.html#focus.
  12. focused,
  13. /// The state when the user is actively pressing down on the given widget.
  14. ///
  15. /// See: https://material.io/design/interaction/states.html#pressed.
  16. pressed,
  17. /// The state when this widget is being dragged from one place to another by
  18. /// the user.
  19. ///
  20. /// https://material.io/design/interaction/states.html#dragged.
  21. dragged,
  22. /// The state when this item has been selected.
  23. ///
  24. /// This applies to things that can be toggled (such as chips and checkboxes)
  25. /// and things that are selected from a set of options (such as tabs and radio buttons).
  26. ///
  27. /// See: https://material.io/design/interaction/states.html#selected.
  28. selected,
  29. /// The state when this widget disabled and can not be interacted with.
  30. ///
  31. /// Disabled widgets should not respond to hover, focus, press, or drag
  32. /// interactions.
  33. ///
  34. /// See: https://material.io/design/interaction/states.html#disabled.
  35. disabled,
  36. /// The state when the widget has entered some form of invalid state.
  37. ///
  38. /// See https://material.io/design/interaction/states.html#usage.
  39. error,
  40. }

下面直接实践,可以看到我默认设置了一个红色,点击状态下为黄色

  1. elevatedButtonTheme: ElevatedButtonThemeData(
  2. style: ButtonStyle(
  3. // backgroundColor: MaterialStateProperty.all(Colors.grey),
  4. backgroundColor:
  5. MaterialStateProperty.resolveWith<Color>((states) {
  6. if (states.contains(MaterialState.pressed)) {
  7. return Colors.yellow;
  8. }
  9. return Colors.red;
  10. }),
  11. ),
  12. )

结果
image.pngimage.png

Api

一共只有3个api,all,resovleAs,resolveWith

all

设置全部状态共同使用的样式

  1. MaterialStateProperty.all<Color>(Colors.grey)

resolveWith

提供回调函数,可以通过实参states去判断不同类型下返回不同的样式,return的值为该泛型

  1. MaterialStateProperty.resolveWith<Color>((states) {
  2. if (states.contains(MaterialState.pressed)) {
  3. return Colors.yellow;
  4. }
  5. return Colors.red;
  6. },
  7. )

resolveAs

没搞懂,网上也没看到相应的demo,忽略