click_opacity.dart 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import 'package:flutter/material.dart';
  2. class ClickOpacity extends StatefulWidget {
  3. final Widget child;
  4. final VoidCallback? onTap;
  5. final VoidCallback? onLongPress;
  6. final double opacity;
  7. final Duration duration;
  8. final bool disabled;
  9. const ClickOpacity({
  10. super.key,
  11. required this.child,
  12. this.onTap,
  13. this.onLongPress,
  14. this.opacity = 0.5,
  15. this.duration = const Duration(milliseconds: 100),
  16. this.disabled = false,
  17. });
  18. @override
  19. State<ClickOpacity> createState() => _ClickOpacityState();
  20. }
  21. class _ClickOpacityState extends State<ClickOpacity> {
  22. bool _isPressed = false;
  23. @override
  24. Widget build(BuildContext context) {
  25. return GestureDetector(
  26. behavior: HitTestBehavior.opaque,
  27. onTapDown: widget.disabled ? null : (_) => _setPressed(true),
  28. onTapUp: widget.disabled ? null : (_) => _setPressed(false),
  29. onTapCancel: widget.disabled ? null : () => _setPressed(false),
  30. onTap: widget.disabled ? null : widget.onTap,
  31. onLongPress: widget.disabled ? null : widget.onLongPress,
  32. child: AnimatedOpacity(
  33. opacity: _isPressed ? widget.opacity : 1.0,
  34. duration: widget.duration,
  35. child: widget.child,
  36. ),
  37. );
  38. }
  39. void _setPressed(bool value) {
  40. if (mounted && _isPressed != value) {
  41. setState(() {
  42. _isPressed = value;
  43. });
  44. }
  45. }
  46. }