import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class GradientButton extends StatelessWidget {
  const GradientButton({
    Key? key,
    this.colors,
    this.linearStart,
    this.linearEnd,
    required this.onPressed,
    required this.child,
    this.padding,
    this.borderRadius = const BorderRadius.all(Radius.circular(2)),
    this.textColor,
    this.splashColor,
    this.disabledColor,
    this.disabledTextColor,
    this.onHighlightChanged,
  }) : super(key: key);

  // 渐变色数组
  final List<Color>? colors;
  final Color? textColor;
  final Color? splashColor;
  final Color? disabledTextColor;
  final Color? disabledColor;
  final EdgeInsetsGeometry? padding;
  final Alignment? linearStart;
  final Alignment? linearEnd;

  final Widget child;
  final BorderRadius? borderRadius;

  final GestureTapCallback? onPressed;
  final ValueChanged<bool>? onHighlightChanged;

  @override
  Widget build(BuildContext context) {
    ThemeData theme = Theme.of(context);
    //确保colors数组不空
    List<Color> _colors =
        colors ?? [theme.primaryColor, theme.primaryColorDark];
    final radius = borderRadius;
    bool disabled = onPressed == null;

    return DecoratedBox(
      decoration: BoxDecoration(
        gradient: disabled ? null : LinearGradient(begin: linearStart??Alignment.topCenter, end: linearEnd??Alignment.bottomCenter, colors: _colors),
        color: disabled ? disabledColor ?? theme.disabledColor : null,
        borderRadius: radius,
      ),
      child: Material(
        type: MaterialType.transparency,
        borderRadius: radius,
        clipBehavior: Clip.hardEdge,
        child: ConstrainedBox(
          constraints: const BoxConstraints(minWidth: 88.0, minHeight: 36.0),
          child: InkWell(
            splashColor: splashColor ?? _colors.last,
            highlightColor: Colors.transparent,
            onHighlightChanged: onHighlightChanged,
            onTap: onPressed,
            child: Padding(
              padding: padding ?? theme.buttonTheme.padding,
              child: DefaultTextStyle(
                style: const TextStyle(fontWeight: FontWeight.bold),
                child: Center(
                  child: DefaultTextStyle(
                    style: theme.textTheme.button!.copyWith(
                      color: disabled
                          ? disabledTextColor ?? Colors.black38
                          : textColor ?? Colors.white,
                    ),
                    child: child,
                  ),
                  widthFactor: 1,
                  heightFactor: 1,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}