scroll_notification_observer.dart 8.49 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:collection';

import 'package:flutter/foundation.dart';

import 'framework.dart';
import 'notification_listener.dart';
import 'scroll_notification.dart';
12
import 'scroll_position.dart';
13

14 15 16 17
// Examples can assume:
// void _listener(ScrollNotification notification) { }
// late BuildContext context;

18 19 20 21 22 23 24 25 26 27
/// A [ScrollNotification] listener for [ScrollNotificationObserver].
///
/// [ScrollNotificationObserver] is similar to
/// [NotificationListener]. It supports a listener list instead of
/// just a single listener and its listeners run unconditionally, they
/// do not require a gating boolean return value.
typedef ScrollNotificationCallback = void Function(ScrollNotification notification);

class _ScrollNotificationObserverScope extends InheritedWidget {
  const _ScrollNotificationObserverScope({
28
    required super.child,
29
    required ScrollNotificationObserverState scrollNotificationObserverState,
30
  }) : _scrollNotificationObserverState = scrollNotificationObserverState;
31 32 33 34 35 36 37

  final ScrollNotificationObserverState  _scrollNotificationObserverState;

  @override
  bool updateShouldNotify(_ScrollNotificationObserverScope old) => _scrollNotificationObserverState != old._scrollNotificationObserverState;
}

38
final class _ListenerEntry extends LinkedListEntry<_ListenerEntry> {
39 40 41 42 43 44 45
  _ListenerEntry(this.listener);
  final ScrollNotificationCallback listener;
}

/// Notifies its listeners when a descendant scrolls.
///
/// To add a listener to a [ScrollNotificationObserver] ancestor:
46
///
47
/// ```dart
48
/// ScrollNotificationObserver.of(context).addListener(_listener);
49 50 51
/// ```
///
/// To remove the listener from a [ScrollNotificationObserver] ancestor:
52
///
53
/// ```dart
54
/// ScrollNotificationObserver.of(context).removeListener(_listener);
55
/// ```
56 57 58 59 60
///
/// Stateful widgets that share an ancestor [ScrollNotificationObserver] typically
/// add a listener in [State.didChangeDependencies] (removing the old one
/// if necessary) and remove the listener in their [State.dispose] method.
///
61 62 63 64 65 66 67 68 69 70 71 72 73
/// Any function with the [ScrollNotificationCallback] signature can act as a
/// listener:
///
/// ```dart
/// // (e.g. in a stateful widget)
/// void _listener(ScrollNotification notification) {
///   // Do something, maybe setState()
/// }
/// ```
///
/// This widget is similar to [NotificationListener]. It supports a listener
/// list instead of just a single listener and its listeners run
/// unconditionally, they do not require a gating boolean return value.
74 75 76 77 78
class ScrollNotificationObserver extends StatefulWidget {
  /// Create a [ScrollNotificationObserver].
  ///
  /// The [child] parameter must not be null.
  const ScrollNotificationObserver({
79
    super.key,
80
    required this.child,
81
  });
82 83 84 85 86 87

  /// The subtree below this widget.
  final Widget child;

  /// The closest instance of this class that encloses the given context.
  ///
88 89 90 91 92 93 94 95 96 97 98
  /// If there is no enclosing [ScrollNotificationObserver] widget, then null is
  /// returned.
  ///
  /// Calling this method will create a dependency on the closest
  /// [ScrollNotificationObserver] in the [context], if there is one.
  ///
  /// See also:
  ///
  /// * [ScrollNotificationObserver.of], which is similar to this method, but
  ///   asserts if no [ScrollNotificationObserver] ancestor is found.
  static ScrollNotificationObserverState? maybeOf(BuildContext context) {
99 100 101
    return context.dependOnInheritedWidgetOfExactType<_ScrollNotificationObserverScope>()?._scrollNotificationObserverState;
  }

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
  /// The closest instance of this class that encloses the given context.
  ///
  /// If no ancestor is found, this method will assert in debug mode, and throw
  /// an exception in release mode.
  ///
  /// Calling this method will create a dependency on the closest
  /// [ScrollNotificationObserver] in the [context].
  ///
  /// See also:
  ///
  /// * [ScrollNotificationObserver.maybeOf], which is similar to this method,
  ///   but returns null if no [ScrollNotificationObserver] ancestor is found.
  static ScrollNotificationObserverState of(BuildContext context) {
    final ScrollNotificationObserverState? observerState = maybeOf(context);
    assert(() {
      if (observerState == null) {
        throw FlutterError(
          'ScrollNotificationObserver.of() was called with a context that does not contain a '
          'ScrollNotificationObserver widget.\n'
          'No ScrollNotificationObserver widget ancestor could be found starting from the '
          'context that was passed to ScrollNotificationObserver.of(). This can happen '
          'because you are using a widget that looks for a ScrollNotificationObserver '
          'ancestor, but no such ancestor exists.\n'
          'The context used was:\n'
          '  $context',
        );
      }
      return true;
    }());
    return observerState!;
  }

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
  @override
  ScrollNotificationObserverState createState() => ScrollNotificationObserverState();
}

/// The listener list state for a [ScrollNotificationObserver] returned by
/// [ScrollNotificationObserver.of].
///
/// [ScrollNotificationObserver] is similar to
/// [NotificationListener]. It supports a listener list instead of
/// just a single listener and its listeners run unconditionally, they
/// do not require a gating boolean return value.
class ScrollNotificationObserverState extends State<ScrollNotificationObserver> {
  LinkedList<_ListenerEntry>? _listeners = LinkedList<_ListenerEntry>();

  bool _debugAssertNotDisposed() {
    assert(() {
      if (_listeners == null) {
        throw FlutterError(
          'A $runtimeType was used after being disposed.\n'
          'Once you have called dispose() on a $runtimeType, it can no longer be used.',
        );
      }
      return true;
    }());
    return true;
  }

  /// Add a [ScrollNotificationCallback] that will be called each time
  /// a descendant scrolls.
  void addListener(ScrollNotificationCallback listener) {
    assert(_debugAssertNotDisposed());
    _listeners!.add(_ListenerEntry(listener));
  }

  /// Remove the specified [ScrollNotificationCallback].
  void removeListener(ScrollNotificationCallback listener) {
    assert(_debugAssertNotDisposed());
    for (final _ListenerEntry entry in _listeners!) {
      if (entry.listener == listener) {
        entry.unlink();
        return;
      }
    }
  }

  void _notifyListeners(ScrollNotification notification) {
    assert(_debugAssertNotDisposed());
181
    if (_listeners!.isEmpty) {
182
      return;
183
    }
184

185
    final List<_ListenerEntry> localListeners = List<_ListenerEntry>.of(_listeners!);
186 187
    for (final _ListenerEntry entry in localListeners) {
      try {
188
        if (entry.list != null) {
189
          entry.listener(notification);
190
        }
191 192 193 194 195 196
      } catch (exception, stack) {
        FlutterError.reportError(FlutterErrorDetails(
          exception: exception,
          stack: stack,
          library: 'widget library',
          context: ErrorDescription('while dispatching notifications for $runtimeType'),
197 198
          informationCollector: () => <DiagnosticsNode>[
            DiagnosticsProperty<ScrollNotificationObserverState>(
199 200 201
              'The $runtimeType sending notification was',
              this,
              style: DiagnosticsTreeStyle.errorProperty,
202 203
            ),
          ],
204 205 206 207 208 209 210
        ));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
211 212 213 214 215 216 217 218 219 220
    // A ScrollMetricsNotification allows listeners to be notified for an
    // initial state, as well as if the content dimensions change without
    // scrolling.
    return NotificationListener<ScrollMetricsNotification>(
      onNotification: (ScrollMetricsNotification notification) {
        _notifyListeners(_ConvertedScrollMetricsNotification(
          metrics: notification.metrics,
          context: notification.context,
          depth: notification.depth,
        ));
221 222
        return false;
      },
223 224 225 226 227 228 229 230 231
      child: NotificationListener<ScrollNotification>(
        onNotification: (ScrollNotification notification) {
          _notifyListeners(notification);
          return false;
        },
        child: _ScrollNotificationObserverScope(
          scrollNotificationObserverState: this,
          child: widget.child,
        ),
232 233 234 235 236 237 238 239 240 241 242
      ),
    );
  }

  @override
  void dispose() {
    assert(_debugAssertNotDisposed());
    _listeners = null;
    super.dispose();
  }
}
243 244 245 246 247 248 249 250

class _ConvertedScrollMetricsNotification extends ScrollUpdateNotification {
  _ConvertedScrollMetricsNotification({
    required super.metrics,
    required super.context,
    required super.depth,
  });
}