scroll_notification_listener.dart 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import 'package:flutter/widgets.dart';
  2. /// 滚动焦点回调
  3. /// focus为是否存在焦点(手指按下放开状态)
  4. typedef ScrollFocusCallback = void Function(bool focus);
  5. /// 滚动事件监听器
  6. class ScrollNotificationListener extends StatefulWidget {
  7. const ScrollNotificationListener({
  8. Key? key,
  9. required this.child,
  10. this.onNotification,
  11. this.onFocus,
  12. }) : super(key: key);
  13. final Widget child;
  14. // 通知回调
  15. final NotificationListenerCallback<ScrollNotification> onNotification;
  16. // 滚动焦点回调
  17. final ScrollFocusCallback onFocus;
  18. @override
  19. ScrollNotificationListenerState createState() {
  20. return ScrollNotificationListenerState();
  21. }
  22. }
  23. class ScrollNotificationListenerState
  24. extends State<ScrollNotificationListener> {
  25. // 焦点状态
  26. bool _focusState = false;
  27. set _focus(bool focus) {
  28. _focusState = focus;
  29. if (widget.onFocus != null) widget.onFocus(_focusState);
  30. }
  31. // 处理滚动通知
  32. void _handleScrollNotification(ScrollNotification notification) {
  33. if (notification is ScrollStartNotification) {
  34. if (notification.dragDetails != null) {
  35. _focus = true;
  36. }
  37. } else if (notification is ScrollUpdateNotification) {
  38. if (_focusState && notification.dragDetails == null) _focus = false;
  39. } else if (notification is ScrollEndNotification) {
  40. if (_focusState) _focus = false;
  41. }
  42. }
  43. @override
  44. Widget build(BuildContext context) =>
  45. NotificationListener<ScrollNotification>(
  46. onNotification: (ScrollNotification notification) {
  47. _handleScrollNotification(notification);
  48. return widget.onNotification == null
  49. ? true
  50. : widget.onNotification(notification);
  51. },
  52. child: widget.child,
  53. );
  54. }