button.dart 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import 'package:flutter/material.dart';
  2. enum VButtonType {
  3. primary,
  4. error,
  5. cancel,
  6. text,
  7. }
  8. class VButton extends StatelessWidget {
  9. /// 类型
  10. final VButtonType type;
  11. /// 文字
  12. final String? label;
  13. /// 自定义子组件
  14. final Widget? child;
  15. /// 点击事件回调
  16. final VoidCallback? onTap;
  17. const VButton({
  18. super.key,
  19. this.type = VButtonType.primary,
  20. this.label,
  21. this.child,
  22. this.onTap,
  23. }) : assert(label != null || child != null);
  24. @override
  25. Widget build(BuildContext context) {
  26. final colors = _findBgColor(context, type);
  27. final bgColor = colors.$1;
  28. final textColor = colors.$2;
  29. return LayoutBuilder(builder: (context, c) {
  30. double width = c.maxWidth;
  31. if (width > 1200) {
  32. width = 270;
  33. }
  34. double height = c.maxHeight;
  35. if (height > 720) {
  36. height = 60;
  37. }
  38. double radius = height / 2;
  39. return SizedBox(
  40. width: 270,
  41. height: height,
  42. child: ElevatedButton(
  43. onPressed: () {
  44. onTap?.call();
  45. },
  46. style: ButtonStyle(
  47. foregroundColor: MaterialStatePropertyAll(textColor),
  48. backgroundColor: MaterialStatePropertyAll(bgColor),
  49. elevation: const MaterialStatePropertyAll(0),
  50. padding: MaterialStatePropertyAll(
  51. EdgeInsets.symmetric(horizontal: radius, vertical: 8),
  52. ),
  53. alignment: Alignment.center,
  54. shape: MaterialStatePropertyAll(
  55. RoundedRectangleBorder(
  56. borderRadius: BorderRadius.circular(radius),
  57. ),
  58. ),
  59. ),
  60. child: child ??
  61. Text(
  62. label!,
  63. style: TextStyle(
  64. color: textColor,
  65. fontSize: 18,
  66. ),
  67. ),
  68. ),
  69. );
  70. });
  71. }
  72. (Color c, Color b) _findBgColor(BuildContext context, VButtonType type) {
  73. switch (type) {
  74. case VButtonType.primary:
  75. return (Theme.of(context).primaryColor, Colors.white);
  76. case VButtonType.error:
  77. return (Theme.of(context).colorScheme.error, Colors.white);
  78. case VButtonType.text:
  79. return (Colors.white, Theme.of(context).primaryColor);
  80. case VButtonType.cancel:
  81. return (Colors.grey, Colors.white);
  82. }
  83. }
  84. }