button.dart 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 SizedBox(
  30. width: 270,
  31. height: 60,
  32. child: ElevatedButton(
  33. onPressed: () {
  34. onTap?.call();
  35. },
  36. style: ButtonStyle(
  37. foregroundColor: MaterialStatePropertyAll(textColor),
  38. backgroundColor: MaterialStatePropertyAll(bgColor),
  39. elevation: const MaterialStatePropertyAll(0),
  40. padding: const MaterialStatePropertyAll(
  41. EdgeInsets.symmetric(horizontal: 14, vertical: 8),
  42. ),
  43. alignment: Alignment.center,
  44. shape: MaterialStatePropertyAll(
  45. RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
  46. ),
  47. ),
  48. child: child ??
  49. Text(
  50. label!,
  51. style: TextStyle(
  52. color: textColor,
  53. fontSize: 18,
  54. ),
  55. ),
  56. ),
  57. );
  58. }
  59. (Color c, Color b) _findBgColor(BuildContext context, VButtonType type) {
  60. switch (type) {
  61. case VButtonType.primary:
  62. return (Theme.of(context).primaryColor, Colors.white);
  63. case VButtonType.error:
  64. return (Theme.of(context).colorScheme.error, Colors.white);
  65. case VButtonType.text:
  66. return (Colors.white, Theme.of(context).primaryColor);
  67. case VButtonType.cancel:
  68. return (Colors.grey, Colors.white);
  69. }
  70. }
  71. }