GradientButton.dart 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 ? null : LinearGradient(begin: linearStart??Alignment.topCenter, end: linearEnd??Alignment.bottomCenter, colors: _colors),
  43. color: disabled ? disabledColor ?? theme.disabledColor : null,
  44. borderRadius: radius,
  45. ),
  46. child: Material(
  47. type: MaterialType.transparency,
  48. borderRadius: radius,
  49. clipBehavior: Clip.hardEdge,
  50. child: ConstrainedBox(
  51. constraints: const BoxConstraints(minWidth: 88.0, minHeight: 36.0),
  52. child: InkWell(
  53. splashColor: splashColor ?? _colors.last,
  54. highlightColor: Colors.transparent,
  55. onHighlightChanged: onHighlightChanged,
  56. onTap: onPressed,
  57. child: Padding(
  58. padding: padding ?? theme.buttonTheme.padding,
  59. child: DefaultTextStyle(
  60. style: const TextStyle(fontWeight: FontWeight.bold),
  61. child: Center(
  62. child: DefaultTextStyle(
  63. style: theme.textTheme.button!.copyWith(
  64. color: disabled
  65. ? disabledTextColor ?? Colors.black38
  66. : textColor ?? Colors.white,
  67. ),
  68. child: child,
  69. ),
  70. widthFactor: 1,
  71. heightFactor: 1,
  72. ),
  73. ),
  74. ),
  75. ),
  76. ),
  77. ),
  78. );
  79. }
  80. }