返回

Flutter 小技巧:ButtonStyle 和 MaterialStateProperty 的妙用

Android

引言

Flutter 2.0 的发布不仅带来了空安全,还带来了令人兴奋的新功能和改进。其中,ButtonStyle 和 MaterialStateProperty 备受关注。它们让自定义按钮变得前所未有地简单,大幅提升了开发效率。

ButtonStyle

ButtonStyle 是一组可用于自定义按钮外观和行为的属性。有了它,你可以轻松设置按钮的背景色、边框、圆角和阴影。

final buttonStyle = ButtonStyle(
  backgroundColor: MaterialStateProperty.all(Colors.blue),
  foregroundColor: MaterialStateProperty.all(Colors.white),
  shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0))),
  elevation: MaterialStateProperty.all(4.0),
);

MaterialStateProperty

MaterialStateProperty 允许你根据按钮的不同状态(如 hover、press、disabled)动态设置样式。

final buttonStyle = ButtonStyle(
  backgroundColor: MaterialStateProperty.resolveWith((states) {
    if (states.contains(MaterialState.hovered)) {
      return Colors.lightBlue;
    } else if (states.contains(MaterialState.pressed)) {
      return Colors.blue[800];
    } else {
      return Colors.blue;
    }
  }),
);

组合使用

将 ButtonStyle 和 MaterialStateProperty 结合使用,你可以创建高度可定制且响应迅速的按钮。

final buttonStyle = ButtonStyle(
  backgroundColor: MaterialStateProperty.resolveWith((states) {
    if (states.contains(MaterialState.hovered)) {
      return Colors.lightBlue;
    } else if (states.contains(MaterialState.pressed)) {
      return Colors.blue[800];
    } else if (states.contains(MaterialState.disabled)) {
      return Colors.grey;
    } else {
      return Colors.blue;
    }
  }),
  foregroundColor: MaterialStateProperty.resolveWith((states) {
    if (states.contains(MaterialState.disabled)) {
      return Colors.black;
    } else {
      return Colors.white;
    }
  }),
  shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0))),
  elevation: MaterialStateProperty.resolveWith((states) {
    if (states.contains(MaterialState.pressed)) {
      return 6.0;
    } else {
      return 4.0;
    }
  }),
);

结语

ButtonStyle 和 MaterialStateProperty 是 Flutter 中强大的工具,它们使自定义按钮变得轻而易举。通过理解和掌握这些特性,你可以创建令人惊叹的按钮,为你的应用增添趣味和互动性。