1 | // Copyright 2014 The Flutter Authors. All rights reserved. |
2 | // Use of this source code is governed by a BSD-style license that can be |
3 | // found in the LICENSE file. |
4 | |
5 | import 'package:flutter/animation.dart'; |
6 | import 'package:flutter/foundation.dart'; |
7 | |
8 | import 'scroll_context.dart'; |
9 | import 'scroll_physics.dart'; |
10 | import 'scroll_position.dart'; |
11 | import 'scroll_position_with_single_context.dart'; |
12 | |
13 | // Examples can assume: |
14 | // TrackingScrollController _trackingScrollController = TrackingScrollController(); |
15 | |
16 | /// Signature for when a [ScrollController] has added or removed a |
17 | /// [ScrollPosition]. |
18 | /// |
19 | /// Since a [ScrollPosition] is not created and attached to a controller until |
20 | /// the [Scrollable] is built, this can be used to respond to the position being |
21 | /// attached to a controller. |
22 | /// |
23 | /// By having access to the position directly, additional listeners can be |
24 | /// applied to aspects of the scroll position, like |
25 | /// [ScrollPosition.isScrollingNotifier]. |
26 | /// |
27 | /// Used by [ScrollController.onAttach] and [ScrollController.onDetach]. |
28 | typedef ScrollControllerCallback = void Function(ScrollPosition position); |
29 | |
30 | /// Controls a scrollable widget. |
31 | /// |
32 | /// Scroll controllers are typically stored as member variables in [State] |
33 | /// objects and are reused in each [State.build]. A single scroll controller can |
34 | /// be used to control multiple scrollable widgets, but some operations, such |
35 | /// as reading the scroll [offset], require the controller to be used with a |
36 | /// single scrollable widget. |
37 | /// |
38 | /// A scroll controller creates a [ScrollPosition] to manage the state specific |
39 | /// to an individual [Scrollable] widget. To use a custom [ScrollPosition], |
40 | /// subclass [ScrollController] and override [createScrollPosition]. |
41 | /// |
42 | /// {@macro flutter.widgets.scrollPosition.listening} |
43 | /// |
44 | /// Typically used with [ListView], [GridView], [CustomScrollView]. |
45 | /// |
46 | /// See also: |
47 | /// |
48 | /// * [ListView], [GridView], [CustomScrollView], which can be controlled by a |
49 | /// [ScrollController]. |
50 | /// * [Scrollable], which is the lower-level widget that creates and associates |
51 | /// [ScrollPosition] objects with [ScrollController] objects. |
52 | /// * [PageController], which is an analogous object for controlling a |
53 | /// [PageView]. |
54 | /// * [ScrollPosition], which manages the scroll offset for an individual |
55 | /// scrolling widget. |
56 | /// * [ScrollNotification] and [NotificationListener], which can be used to |
57 | /// listen to scrolling occur without using a [ScrollController]. |
58 | class ScrollController extends ChangeNotifier { |
59 | /// Creates a controller for a scrollable widget. |
60 | ScrollController({ |
61 | double initialScrollOffset = 0.0, |
62 | this.keepScrollOffset = true, |
63 | this.debugLabel, |
64 | this.onAttach, |
65 | this.onDetach, |
66 | }) : _initialScrollOffset = initialScrollOffset { |
67 | if (kFlutterMemoryAllocationsEnabled) { |
68 | ChangeNotifier.maybeDispatchObjectCreation(this); |
69 | } |
70 | } |
71 | |
72 | /// The initial value to use for [offset]. |
73 | /// |
74 | /// New [ScrollPosition] objects that are created and attached to this |
75 | /// controller will have their offset initialized to this value |
76 | /// if [keepScrollOffset] is false or a scroll offset hasn't been saved yet. |
77 | /// |
78 | /// Defaults to 0.0. |
79 | double get initialScrollOffset => _initialScrollOffset; |
80 | final double _initialScrollOffset; |
81 | |
82 | /// Each time a scroll completes, save the current scroll [offset] with |
83 | /// [PageStorage] and restore it if this controller's scrollable is recreated. |
84 | /// |
85 | /// If this property is set to false, the scroll offset is never saved |
86 | /// and [initialScrollOffset] is always used to initialize the scroll |
87 | /// offset. If true (the default), the initial scroll offset is used the |
88 | /// first time the controller's scrollable is created, since there's no |
89 | /// scroll offset to restore yet. Subsequently the saved offset is |
90 | /// restored and [initialScrollOffset] is ignored. |
91 | /// |
92 | /// See also: |
93 | /// |
94 | /// * [PageStorageKey], which should be used when more than one |
95 | /// scrollable appears in the same route, to distinguish the [PageStorage] |
96 | /// locations used to save scroll offsets. |
97 | final bool keepScrollOffset; |
98 | |
99 | /// Called when a [ScrollPosition] is attached to the scroll controller. |
100 | /// |
101 | /// Since a scroll position is not attached until a [Scrollable] is actually |
102 | /// built, this can be used to respond to a new position being attached. |
103 | /// |
104 | /// At the time that a scroll position is attached, the [ScrollMetrics], such as |
105 | /// the [ScrollMetrics.maxScrollExtent], are not yet available. These are not |
106 | /// determined until the [Scrollable] has finished laying out its contents and |
107 | /// computing things like the full extent of that content. |
108 | /// [ScrollPosition.hasContentDimensions] can be used to know when the |
109 | /// metrics are available, or a [ScrollMetricsNotification] can be used, |
110 | /// discussed further below. |
111 | /// |
112 | /// {@tool dartpad} |
113 | /// This sample shows how to apply a listener to the |
114 | /// [ScrollPosition.isScrollingNotifier] using [ScrollController.onAttach]. |
115 | /// This is used to change the [AppBar]'s color when scrolling is occurring. |
116 | /// |
117 | /// ** See code in examples/api/lib/widgets/scroll_position/scroll_controller_on_attach.0.dart ** |
118 | /// {@end-tool} |
119 | final ScrollControllerCallback? onAttach; |
120 | |
121 | /// Called when a [ScrollPosition] is detached from the scroll controller. |
122 | /// |
123 | /// {@tool dartpad} |
124 | /// This sample shows how to apply a listener to the |
125 | /// [ScrollPosition.isScrollingNotifier] using [ScrollController.onAttach] |
126 | /// & [ScrollController.onDetach]. |
127 | /// This is used to change the [AppBar]'s color when scrolling is occurring. |
128 | /// |
129 | /// ** See code in examples/api/lib/widgets/scroll_position/scroll_controller_on_attach.0.dart ** |
130 | /// {@end-tool} |
131 | final ScrollControllerCallback? onDetach; |
132 | |
133 | /// A label that is used in the [toString] output. Intended to aid with |
134 | /// identifying scroll controller instances in debug output. |
135 | final String? debugLabel; |
136 | |
137 | /// The currently attached positions. |
138 | /// |
139 | /// This should not be mutated directly. [ScrollPosition] objects can be added |
140 | /// and removed using [attach] and [detach]. |
141 | Iterable<ScrollPosition> get positions => _positions; |
142 | final List<ScrollPosition> _positions = <ScrollPosition>[]; |
143 | |
144 | /// Whether any [ScrollPosition] objects have attached themselves to the |
145 | /// [ScrollController] using the [attach] method. |
146 | /// |
147 | /// If this is false, then members that interact with the [ScrollPosition], |
148 | /// such as [position], [offset], [animateTo], and [jumpTo], must not be |
149 | /// called. |
150 | bool get hasClients => _positions.isNotEmpty; |
151 | |
152 | /// Returns the attached [ScrollPosition], from which the actual scroll offset |
153 | /// of the [ScrollView] can be obtained. |
154 | /// |
155 | /// Calling this is only valid when only a single position is attached. |
156 | ScrollPosition get position { |
157 | assert(_positions.isNotEmpty, 'ScrollController not attached to any scroll views.' ); |
158 | assert(_positions.length == 1, 'ScrollController attached to multiple scroll views.' ); |
159 | return _positions.single; |
160 | } |
161 | |
162 | /// The current scroll offset of the scrollable widget. |
163 | /// |
164 | /// Requires the controller to be controlling exactly one scrollable widget. |
165 | double get offset => position.pixels; |
166 | |
167 | /// Animates the position from its current value to the given value. |
168 | /// |
169 | /// Any active animation is canceled. If the user is currently scrolling, that |
170 | /// action is canceled. |
171 | /// |
172 | /// The returned [Future] will complete when the animation ends, whether it |
173 | /// completed successfully or whether it was interrupted prematurely. |
174 | /// |
175 | /// An animation will be interrupted whenever the user attempts to scroll |
176 | /// manually, or whenever another activity is started, or whenever the |
177 | /// animation reaches the edge of the viewport and attempts to overscroll. (If |
178 | /// the [ScrollPosition] does not overscroll but instead allows scrolling |
179 | /// beyond the extents, then going beyond the extents will not interrupt the |
180 | /// animation.) |
181 | /// |
182 | /// The animation is indifferent to changes to the viewport or content |
183 | /// dimensions. |
184 | /// |
185 | /// Once the animation has completed, the scroll position will attempt to |
186 | /// begin a ballistic activity in case its value is not stable (for example, |
187 | /// if it is scrolled beyond the extents and in that situation the scroll |
188 | /// position would normally bounce back). |
189 | /// |
190 | /// The duration must not be zero. To jump to a particular value without an |
191 | /// animation, use [jumpTo]. |
192 | /// |
193 | /// When calling [animateTo] in widget tests, `await`ing the returned |
194 | /// [Future] may cause the test to hang and timeout. Instead, use |
195 | /// [WidgetTester.pumpAndSettle]. |
196 | Future<void> animateTo( |
197 | double offset, { |
198 | required Duration duration, |
199 | required Curve curve, |
200 | }) async { |
201 | assert(_positions.isNotEmpty, 'ScrollController not attached to any scroll views.' ); |
202 | await Future.wait<void>(<Future<void>>[ |
203 | for (int i = 0; i < _positions.length; i += 1) _positions[i].animateTo(offset, duration: duration, curve: curve), |
204 | ]); |
205 | } |
206 | |
207 | /// Jumps the scroll position from its current value to the given value, |
208 | /// without animation, and without checking if the new value is in range. |
209 | /// |
210 | /// Any active animation is canceled. If the user is currently scrolling, that |
211 | /// action is canceled. |
212 | /// |
213 | /// If this method changes the scroll position, a sequence of start/update/end |
214 | /// scroll notifications will be dispatched. No overscroll notifications can |
215 | /// be generated by this method. |
216 | /// |
217 | /// Immediately after the jump, a ballistic activity is started, in case the |
218 | /// value was out of range. |
219 | void jumpTo(double value) { |
220 | assert(_positions.isNotEmpty, 'ScrollController not attached to any scroll views.' ); |
221 | for (final ScrollPosition position in List<ScrollPosition>.of(_positions)) { |
222 | position.jumpTo(value); |
223 | } |
224 | } |
225 | |
226 | /// Register the given position with this controller. |
227 | /// |
228 | /// After this function returns, the [animateTo] and [jumpTo] methods on this |
229 | /// controller will manipulate the given position. |
230 | void attach(ScrollPosition position) { |
231 | assert(!_positions.contains(position)); |
232 | _positions.add(position); |
233 | position.addListener(notifyListeners); |
234 | if (onAttach != null) { |
235 | onAttach!(position); |
236 | } |
237 | } |
238 | |
239 | /// Unregister the given position with this controller. |
240 | /// |
241 | /// After this function returns, the [animateTo] and [jumpTo] methods on this |
242 | /// controller will not manipulate the given position. |
243 | void detach(ScrollPosition position) { |
244 | assert(_positions.contains(position)); |
245 | if (onDetach != null) { |
246 | onDetach!(position); |
247 | } |
248 | position.removeListener(notifyListeners); |
249 | _positions.remove(position); |
250 | } |
251 | |
252 | @override |
253 | void dispose() { |
254 | for (final ScrollPosition position in _positions) { |
255 | position.removeListener(notifyListeners); |
256 | } |
257 | super.dispose(); |
258 | } |
259 | |
260 | /// Creates a [ScrollPosition] for use by a [Scrollable] widget. |
261 | /// |
262 | /// Subclasses can override this function to customize the [ScrollPosition] |
263 | /// used by the scrollable widgets they control. For example, [PageController] |
264 | /// overrides this function to return a page-oriented scroll position |
265 | /// subclass that keeps the same page visible when the scrollable widget |
266 | /// resizes. |
267 | /// |
268 | /// By default, returns a [ScrollPositionWithSingleContext]. |
269 | /// |
270 | /// The arguments are generally passed to the [ScrollPosition] being created: |
271 | /// |
272 | /// * `physics`: An instance of [ScrollPhysics] that determines how the |
273 | /// [ScrollPosition] should react to user interactions, how it should |
274 | /// simulate scrolling when released or flung, etc. The value will not be |
275 | /// null. It typically comes from the [ScrollView] or other widget that |
276 | /// creates the [Scrollable], or, if none was provided, from the ambient |
277 | /// [ScrollConfiguration]. |
278 | /// * `context`: A [ScrollContext] used for communicating with the object |
279 | /// that is to own the [ScrollPosition] (typically, this is the |
280 | /// [Scrollable] itself). |
281 | /// * `oldPosition`: If this is not the first time a [ScrollPosition] has |
282 | /// been created for this [Scrollable], this will be the previous instance. |
283 | /// This is used when the environment has changed and the [Scrollable] |
284 | /// needs to recreate the [ScrollPosition] object. It is null the first |
285 | /// time the [ScrollPosition] is created. |
286 | ScrollPosition createScrollPosition( |
287 | ScrollPhysics physics, |
288 | ScrollContext context, |
289 | ScrollPosition? oldPosition, |
290 | ) { |
291 | return ScrollPositionWithSingleContext( |
292 | physics: physics, |
293 | context: context, |
294 | initialPixels: initialScrollOffset, |
295 | keepScrollOffset: keepScrollOffset, |
296 | oldPosition: oldPosition, |
297 | debugLabel: debugLabel, |
298 | ); |
299 | } |
300 | |
301 | @override |
302 | String toString() { |
303 | final List<String> description = <String>[]; |
304 | debugFillDescription(description); |
305 | return ' ${describeIdentity(this)}( ${description.join(", " )})' ; |
306 | } |
307 | |
308 | /// Add additional information to the given description for use by [toString]. |
309 | /// |
310 | /// This method makes it easier for subclasses to coordinate to provide a |
311 | /// high-quality [toString] implementation. The [toString] implementation on |
312 | /// the [ScrollController] base class calls [debugFillDescription] to collect |
313 | /// useful information from subclasses to incorporate into its return value. |
314 | /// |
315 | /// Implementations of this method should start with a call to the inherited |
316 | /// method, as in `super.debugFillDescription(description)`. |
317 | @mustCallSuper |
318 | void debugFillDescription(List<String> description) { |
319 | if (debugLabel != null) { |
320 | description.add(debugLabel!); |
321 | } |
322 | if (initialScrollOffset != 0.0) { |
323 | description.add('initialScrollOffset: ${initialScrollOffset.toStringAsFixed(1)}, ' ); |
324 | } |
325 | if (_positions.isEmpty) { |
326 | description.add('no clients' ); |
327 | } else if (_positions.length == 1) { |
328 | // Don't actually list the client itself, since its toString may refer to us. |
329 | description.add('one client, offset ${offset.toStringAsFixed(1)}' ); |
330 | } else { |
331 | description.add(' ${_positions.length} clients' ); |
332 | } |
333 | } |
334 | } |
335 | |
336 | // Examples can assume: |
337 | // TrackingScrollController? _trackingScrollController; |
338 | |
339 | /// A [ScrollController] whose [initialScrollOffset] tracks its most recently |
340 | /// updated [ScrollPosition]. |
341 | /// |
342 | /// This class can be used to synchronize the scroll offset of two or more |
343 | /// lazily created scroll views that share a single [TrackingScrollController]. |
344 | /// It tracks the most recently updated scroll position and reports it as its |
345 | /// `initialScrollOffset`. |
346 | /// |
347 | /// {@tool snippet} |
348 | /// |
349 | /// In this example each [PageView] page contains a [ListView] and all three |
350 | /// [ListView]'s share a [TrackingScrollController]. The scroll offsets of all |
351 | /// three list views will track each other, to the extent that's possible given |
352 | /// the different list lengths. |
353 | /// |
354 | /// ```dart |
355 | /// PageView( |
356 | /// children: <Widget>[ |
357 | /// ListView( |
358 | /// controller: _trackingScrollController, |
359 | /// children: List<Widget>.generate(100, (int i) => Text('page 0 item $i')).toList(), |
360 | /// ), |
361 | /// ListView( |
362 | /// controller: _trackingScrollController, |
363 | /// children: List<Widget>.generate(200, (int i) => Text('page 1 item $i')).toList(), |
364 | /// ), |
365 | /// ListView( |
366 | /// controller: _trackingScrollController, |
367 | /// children: List<Widget>.generate(300, (int i) => Text('page 2 item $i')).toList(), |
368 | /// ), |
369 | /// ], |
370 | /// ) |
371 | /// ``` |
372 | /// {@end-tool} |
373 | /// |
374 | /// In this example the `_trackingController` would have been created by the |
375 | /// stateful widget that built the widget tree. |
376 | class TrackingScrollController extends ScrollController { |
377 | /// Creates a scroll controller that continually updates its |
378 | /// [initialScrollOffset] to match the last scroll notification it received. |
379 | TrackingScrollController({ |
380 | super.initialScrollOffset, |
381 | super.keepScrollOffset, |
382 | super.debugLabel, |
383 | super.onAttach, |
384 | super.onDetach, |
385 | }); |
386 | |
387 | final Map<ScrollPosition, VoidCallback> _positionToListener = <ScrollPosition, VoidCallback>{}; |
388 | ScrollPosition? _lastUpdated; |
389 | double? _lastUpdatedOffset; |
390 | |
391 | /// The last [ScrollPosition] to change. Returns null if there aren't any |
392 | /// attached scroll positions, or there hasn't been any scrolling yet, or the |
393 | /// last [ScrollPosition] to change has since been removed. |
394 | ScrollPosition? get mostRecentlyUpdatedPosition => _lastUpdated; |
395 | |
396 | /// Returns the scroll offset of the [mostRecentlyUpdatedPosition] or, if that |
397 | /// is null, the initial scroll offset provided to the constructor. |
398 | /// |
399 | /// See also: |
400 | /// |
401 | /// * [ScrollController.initialScrollOffset], which this overrides. |
402 | @override |
403 | double get initialScrollOffset => _lastUpdatedOffset ?? super.initialScrollOffset; |
404 | |
405 | @override |
406 | void attach(ScrollPosition position) { |
407 | super.attach(position); |
408 | assert(!_positionToListener.containsKey(position)); |
409 | _positionToListener[position] = () { |
410 | _lastUpdated = position; |
411 | _lastUpdatedOffset = position.pixels; |
412 | }; |
413 | position.addListener(_positionToListener[position]!); |
414 | } |
415 | |
416 | @override |
417 | void detach(ScrollPosition position) { |
418 | super.detach(position); |
419 | assert(_positionToListener.containsKey(position)); |
420 | position.removeListener(_positionToListener[position]!); |
421 | _positionToListener.remove(position); |
422 | if (_lastUpdated == position) { |
423 | _lastUpdated = null; |
424 | } |
425 | if (_positionToListener.isEmpty) { |
426 | _lastUpdatedOffset = null; |
427 | } |
428 | } |
429 | |
430 | @override |
431 | void dispose() { |
432 | for (final ScrollPosition position in positions) { |
433 | assert(_positionToListener.containsKey(position)); |
434 | position.removeListener(_positionToListener[position]!); |
435 | } |
436 | super.dispose(); |
437 | } |
438 | } |
439 | |