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