GradientButton.dart 2.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import 'package:flutter/material.dart';
  2. import 'package:flutter/widgets.dart';
  3. class GradientButton extends StatelessWidget {
  4. const GradientButton({
  5. Key? key,
  6. this.colors,
  7. this.linearStart,
  8. this.linearEnd,
  9. required this.onPressed,
  10. required this.child,
  11. this.padding,
  12. this.borderRadius = const BorderRadius.all(Radius.circular(2)),
  13. this.textColor,
  14. this.splashColor,
  15. this.disabledColor,
  16. this.disabledTextColor,
  17. this.onHighlightChanged,
  18. }) : super(key: key);
  19. // 渐变色数组
  20. final List<Color>? colors;
  21. final Color? textColor;
  22. final Color? splashColor;
  23. final Color? disabledTextColor;
  24. final Color? disabledColor;
  25. final EdgeInsetsGeometry? padding;
  26. final Alignment? linearStart;
  27. final Alignment? linearEnd;
  28. final Widget child;
  29. final BorderRadius? borderRadius;
  30. final GestureTapCallback? onPressed;
  31. final ValueChanged<bool>? onHighlightChanged;
  32. @override
  33. Widget build(BuildContext context) {
  34. ThemeData theme = Theme.of(context);
  35. //确保colors数组不空
  36. List<Color> _colors =
  37. colors ?? [theme.primaryColor, theme.primaryColorDark];
  38. final radius = borderRadius;
  39. bool disabled = onPressed == null;
  40. return DecoratedBox(
  41. decoration: BoxDecoration(
  42. gradient: disabled
  43. ? null
  44. : LinearGradient(
  45. begin: linearStart ?? Alignment.topCenter,
  46. end: linearEnd ?? Alignment.bottomCenter,
  47. colors: _colors),
  48. color: disabled ? disabledColor ?? theme.disabledColor : null,
  49. borderRadius: radius,
  50. ),
  51. child: Material(
  52. type: MaterialType.transparency,
  53. borderRadius: radius,
  54. clipBehavior: Clip.hardEdge,
  55. child: ConstrainedBox(
  56. constraints: const BoxConstraints(minWidth: 88.0, minHeight: 36.0),
  57. child: InkWell(
  58. splashColor: splashColor ?? _colors.last,
  59. highlightColor: Colors.transparent,
  60. onHighlightChanged: onHighlightChanged,
  61. onTap: onPressed,
  62. child: Padding(
  63. padding: padding ?? theme.buttonTheme.padding,
  64. child: DefaultTextStyle(
  65. style: const TextStyle(fontWeight: FontWeight.bold),
  66. child: Center(
  67. child: DefaultTextStyle(
  68. style: theme.textTheme.button!.copyWith(
  69. color: disabled
  70. ? disabledTextColor ?? Colors.black38
  71. : textColor ?? Colors.white,
  72. ),
  73. child: child,
  74. ),
  75. widthFactor: 1,
  76. heightFactor: 1,
  77. ),
  78. ),
  79. ),
  80. ),
  81. ),
  82. ),
  83. );
  84. }
  85. }