scroll_physics.dart 37.6 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:math' as math;

7 8
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
9 10
import 'package:flutter/physics.dart';

11
import 'binding.dart' show WidgetsBinding;
12
import 'framework.dart';
13
import 'overscroll_indicator.dart';
14
import 'scroll_metrics.dart';
15
import 'scroll_simulation.dart';
16

17
export 'package:flutter/physics.dart' show ScrollSpringSimulation, Simulation, Tolerance;
18

19 20 21 22 23 24 25 26 27 28 29
/// The rate at which scroll momentum will be decelerated.
enum ScrollDecelerationRate {
  /// Standard deceleration, aligned with mobile software expectations.
  normal,
  /// Increased deceleration, aligned with desktop software expectations.
  ///
  /// Appropriate for use with input devices more precise than touch screens,
  /// such as trackpads or mouse wheels.
  fast
}

30 31
// Examples can assume:
// class FooScrollPhysics extends ScrollPhysics {
32
//   const FooScrollPhysics({ super.parent });
33 34 35 36
//   @override
//   FooScrollPhysics applyTo(ScrollPhysics? ancestor) {
//     return FooScrollPhysics(parent: buildParent(ancestor));
//   }
37 38
// }
// class BarScrollPhysics extends ScrollPhysics {
39
//   const BarScrollPhysics({ super.parent });
40 41
// }

42 43 44 45 46 47 48 49 50
/// Determines the physics of a [Scrollable] widget.
///
/// For example, determines how the [Scrollable] will behave when the user
/// reaches the maximum scroll extent or when the user stops scrolling.
///
/// When starting a physics [Simulation], the current scroll position and
/// velocity are used as the initial conditions for the particle in the
/// simulation. The movement of the particle in the simulation is then used to
/// determine the scroll position for the widget.
51 52 53
///
/// Instead of creating your own subclasses, [parent] can be used to combine
/// [ScrollPhysics] objects of different types to get the desired scroll physics.
54 55 56 57 58 59 60
/// For example:
///
/// ```dart
/// const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics())
/// ```
///
/// You can also use `applyTo`, which is useful when you already have
61
/// an instance of [ScrollPhysics]:
62 63 64 65
///
/// ```dart
/// ScrollPhysics physics = const BouncingScrollPhysics();
/// // ...
66
/// final ScrollPhysics mergedPhysics = physics.applyTo(const AlwaysScrollableScrollPhysics());
67
/// ```
68
@immutable
69
class ScrollPhysics {
70
  /// Creates an object with the default scroll physics.
71
  const ScrollPhysics({ this.parent });
72

73 74 75 76 77
  /// If non-null, determines the default behavior for each method.
  ///
  /// If a subclass of [ScrollPhysics] does not override a method, that subclass
  /// will inherit an implementation from this base class that defers to
  /// [parent]. This mechanism lets you assemble novel combinations of
78 79 80
  /// [ScrollPhysics] subclasses at runtime. For example:
  ///
  /// ```dart
81
  /// const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics())
82
  /// ```
83
  ///
84 85 86 87
  /// will result in a [ScrollPhysics] that has the combined behavior
  /// of [BouncingScrollPhysics] and [AlwaysScrollableScrollPhysics]:
  /// behaviors that are not specified in [BouncingScrollPhysics]
  /// (e.g. [shouldAcceptUserOffset]) will defer to [AlwaysScrollableScrollPhysics].
88
  final ScrollPhysics? parent;
89

90 91 92 93
  /// If [parent] is null then return ancestor, otherwise recursively build a
  /// ScrollPhysics that has [ancestor] as its parent.
  ///
  /// This method is typically used to define [applyTo] methods like:
94
  ///
95
  /// ```dart
96 97 98 99 100 101 102 103 104
  /// class MyScrollPhysics extends ScrollPhysics {
  ///   const MyScrollPhysics({ super.parent });
  ///
  ///   @override
  ///   MyScrollPhysics applyTo(ScrollPhysics? ancestor) {
  ///     return MyScrollPhysics(parent: buildParent(ancestor));
  ///   }
  ///
  ///   // ...
105 106 107
  /// }
  /// ```
  @protected
108
  ScrollPhysics? buildParent(ScrollPhysics? ancestor) => parent?.applyTo(ancestor) ?? ancestor;
109

110
  /// Combines this [ScrollPhysics] instance with the given physics.
111
  ///
112 113 114
  /// The returned object uses this instance's physics when it has an
  /// opinion, and defers to the given `ancestor` object's physics
  /// when it does not.
115
  ///
116 117 118 119 120 121 122 123 124 125
  /// If [parent] is null then this returns a [ScrollPhysics] with the
  /// same [runtimeType], but where the [parent] has been replaced
  /// with the [ancestor].
  ///
  /// If this scroll physics object already has a parent, then this
  /// method is applied recursively and ancestor will appear at the
  /// end of the existing chain of parents.
  ///
  /// Calling this method with a null argument will copy the current
  /// object. This is inefficient.
126
  ///
127
  /// {@tool snippet}
128 129
  ///
  /// In the following example, the [applyTo] method is used to combine the
130 131
  /// scroll physics of two [ScrollPhysics] objects. The resulting [ScrollPhysics]
  /// `x` has the same behavior as `y`.
132 133
  ///
  /// ```dart
134
  /// final FooScrollPhysics x = const FooScrollPhysics().applyTo(const BarScrollPhysics());
135 136 137 138
  /// const FooScrollPhysics y = FooScrollPhysics(parent: BarScrollPhysics());
  /// ```
  /// {@end-tool}
  ///
139
  /// ## Implementing [applyTo]
140 141 142 143 144 145 146 147
  ///
  /// When creating a custom [ScrollPhysics] subclass, this method
  /// must be implemented. If the physics class has no constructor
  /// arguments, then implementing this method is merely a matter of
  /// calling the constructor with a [parent] constructed using
  /// [buildParent], as follows:
  ///
  /// ```dart
148 149 150 151 152 153 154 155 156
  /// class MyScrollPhysics extends ScrollPhysics {
  ///   const MyScrollPhysics({ super.parent });
  ///
  ///   @override
  ///   MyScrollPhysics applyTo(ScrollPhysics? ancestor) {
  ///     return MyScrollPhysics(parent: buildParent(ancestor));
  ///   }
  ///
  ///   // ...
157 158 159 160 161 162
  /// }
  /// ```
  ///
  /// If the physics class has constructor arguments, they must be passed to
  /// the constructor here as well, so as to create a clone.
  ///
163 164
  /// See also:
  ///
165
  ///  * [buildParent], a utility method that's often used to define [applyTo]
166
  ///    methods for [ScrollPhysics] subclasses.
167
  ScrollPhysics applyTo(ScrollPhysics? ancestor) {
168
    return ScrollPhysics(parent: buildParent(ancestor));
169
  }
170

171 172 173 174
  /// Used by [DragScrollActivity] and other user-driven activities to convert
  /// an offset in logical pixels as provided by the [DragUpdateDetails] into a
  /// delta to apply (subtract from the current position) using
  /// [ScrollActivityDelegate.setPixels].
175 176 177 178 179 180 181 182 183 184 185
  ///
  /// This is used by some [ScrollPosition] subclasses to apply friction during
  /// overscroll situations.
  ///
  /// This method must not adjust parts of the offset that are entirely within
  /// the bounds described by the given `position`.
  ///
  /// The given `position` is only valid during this method call. Do not keep a
  /// reference to it to use later, as the values may update, may not update, or
  /// may update to reflect an entirely unrelated scrollable.
  double applyPhysicsToUserOffset(ScrollMetrics position, double offset) {
186
    if (parent == null) {
187
      return offset;
188
    }
189
    return parent!.applyPhysicsToUserOffset(position, offset);
190 191 192 193 194 195 196 197 198 199 200 201
  }

  /// Whether the scrollable should let the user adjust the scroll offset, for
  /// example by dragging.
  ///
  /// By default, the user can manipulate the scroll offset if, and only if,
  /// there is actually content outside the viewport to reveal.
  ///
  /// The given `position` is only valid during this method call. Do not keep a
  /// reference to it to use later, as the values may update, may not update, or
  /// may update to reflect an entirely unrelated scrollable.
  bool shouldAcceptUserOffset(ScrollMetrics position) {
202
    if (parent == null) {
203
      return position.pixels != 0.0 || position.minScrollExtent != position.maxScrollExtent;
204
    }
205
    return parent!.shouldAcceptUserOffset(position);
206 207
  }

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
  /// Provides a heuristic to determine if expensive frame-bound tasks should be
  /// deferred.
  ///
  /// The velocity parameter must not be null, but may be positive, negative, or
  /// zero.
  ///
  /// The metrics parameter must not be null.
  ///
  /// The context parameter must not be null. It normally refers to the
  /// [BuildContext] of the widget making the call, such as an [Image] widget
  /// in a [ListView].
  ///
  /// This can be used to determine whether decoding or fetching complex data
  /// for the currently visible part of the viewport should be delayed
  /// to avoid doing work that will not have a chance to appear before a new
  /// frame is rendered.
  ///
  /// For example, a list of images could use this logic to delay decoding
  /// images until scrolling is slow enough to actually render the decoded
  /// image to the screen.
  ///
  /// The default implementation is a heuristic that compares the current
  /// scroll velocity in local logical pixels to the longest side of the window
  /// in physical pixels. Implementers can change this heuristic by overriding
  /// this method and providing their custom physics to the scrollable widget.
  /// For example, an application that changes the local coordinate system with
  /// a large perspective transform could provide a more or less aggressive
  /// heuristic depending on whether the transform was increasing or decreasing
  /// the overall scale between the global screen and local scrollable
  /// coordinate systems.
  ///
  /// The default implementation is stateless, and simply provides a point-in-
  /// time decision about how fast the scrollable is scrolling. It would always
  /// return true for a scrollable that is animating back and forth at high
  /// velocity in a loop. It is assumed that callers will handle such
  /// a case, or that a custom stateful implementation would be written that
  /// tracks the sign of the velocity on successive calls.
  ///
  /// Returning true from this method indicates that the current scroll velocity
  /// is great enough that expensive operations impacting the UI should be
  /// deferred.
  bool recommendDeferredLoading(double velocity, ScrollMetrics metrics, BuildContext context) {
    assert(velocity != null);
    assert(metrics != null);
    assert(context != null);
    if (parent == null) {
254
      final double maxPhysicalPixels = WidgetsBinding.instance.window.physicalSize.longestSide;
255 256
      return velocity.abs() > maxPhysicalPixels;
    }
257
    return parent!.recommendDeferredLoading(velocity, metrics, context);
258 259
  }

260 261
  /// Determines the overscroll by applying the boundary conditions.
  ///
262 263 264 265
  /// Called by [ScrollPosition.applyBoundaryConditions], which is called by
  /// [ScrollPosition.setPixels] just before the [ScrollPosition.pixels] value
  /// is updated, to determine how much of the offset is to be clamped off and
  /// sent to [ScrollPosition.didOverscrollBy].
266
  ///
267 268
  /// The `value` argument is guaranteed to not equal the [ScrollMetrics.pixels]
  /// of the `position` argument when this is called.
269
  ///
270
  /// It is possible for this method to be called when the `position` describes
271 272 273 274 275 276 277 278 279 280 281 282
  /// an already-out-of-bounds position. In that case, the boundary conditions
  /// should usually only prevent a further increase in the extent to which the
  /// position is out of bounds, allowing a decrease to be applied successfully,
  /// so that (for instance) an animation can smoothly snap an out of bounds
  /// position to the bounds. See [BallisticScrollActivity].
  ///
  /// This method must not clamp parts of the offset that are entirely within
  /// the bounds described by the given `position`.
  ///
  /// The given `position` is only valid during this method call. Do not keep a
  /// reference to it to use later, as the values may update, may not update, or
  /// may update to reflect an entirely unrelated scrollable.
283 284 285 286 287 288 289 290 291 292 293
  ///
  /// ## Examples
  ///
  /// [BouncingScrollPhysics] returns zero. In other words, it allows scrolling
  /// past the boundary unhindered.
  ///
  /// [ClampingScrollPhysics] returns the amount by which the value is beyond
  /// the position or the boundary, whichever is furthest from the content. In
  /// other words, it disallows scrolling past the boundary, but allows
  /// scrolling back from being overscrolled, if for some reason the position
  /// ends up overscrolled.
294
  double applyBoundaryConditions(ScrollMetrics position, double value) {
295
    if (parent == null) {
296
      return 0.0;
297
    }
298
    return parent!.applyBoundaryConditions(position, value);
299 300
  }

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
  /// Describes what the scroll position should be given new viewport dimensions.
  ///
  /// This is called by [ScrollPosition.correctForNewDimensions].
  ///
  /// The arguments consist of the scroll metrics as they stood in the previous
  /// frame and the scroll metrics as they now stand after the last layout,
  /// including the position and minimum and maximum scroll extents; a flag
  /// indicating if the current [ScrollActivity] considers that the user is
  /// actively scrolling (see [ScrollActivity.isScrolling]); and the current
  /// velocity of the scroll position, if it is being driven by the scroll
  /// activity (this is 0.0 during a user gesture) (see
  /// [ScrollActivity.velocity]).
  ///
  /// The scroll metrics will be identical except for the
  /// [ScrollMetrics.minScrollExtent] and [ScrollMetrics.maxScrollExtent]. They
  /// are referred to as the `oldPosition` and `newPosition` (even though they
  /// both technically have the same "position", in the form of
  /// [ScrollMetrics.pixels]) because they are generated from the
  /// [ScrollPosition] before and after updating the scroll extents.
  ///
  /// If the returned value does not exactly match the scroll offset given by
  /// the `newPosition` argument (see [ScrollMetrics.pixels]), then the
  /// [ScrollPosition] will call [ScrollPosition.correctPixels] to update the
  /// new scroll position to the returned value, and layout will be re-run. This
  /// is expensive. The new value is subject to further manipulation by
  /// [applyBoundaryConditions].
  ///
  /// If the returned value _does_ match the `newPosition.pixels` scroll offset
  /// exactly, then [ScrollPosition.applyNewDimensions] will be called next. In
  /// that case, [applyBoundaryConditions] is not applied to the return value.
  ///
  /// The given [ScrollMetrics] are only valid during this method call. Do not
  /// keep references to them to use later, as the values may update, may not
  /// update, or may update to reflect an entirely unrelated scrollable.
  ///
  /// The default implementation returns the [ScrollMetrics.pixels] of the
  /// `newPosition`, which indicates that the current scroll offset is
  /// acceptable.
  ///
  /// See also:
  ///
  ///  * [RangeMaintainingScrollPhysics], which is enabled by default, and
  ///    which prevents unexpected changes to the content dimensions from
  ///    causing the scroll position to get any further out of bounds.
  double adjustPositionForNewDimensions({
346 347 348 349
    required ScrollMetrics oldPosition,
    required ScrollMetrics newPosition,
    required bool isScrolling,
    required double velocity,
350
  }) {
351
    if (parent == null) {
352
      return newPosition.pixels;
353
    }
354
    return parent!.adjustPositionForNewDimensions(oldPosition: oldPosition, newPosition: newPosition, isScrolling: isScrolling, velocity: velocity);
355 356
  }

357
  /// Returns a simulation for ballistic scrolling starting from the given
358 359 360 361 362 363 364 365 366 367 368
  /// position with the given velocity.
  ///
  /// This is used by [ScrollPositionWithSingleContext] in the
  /// [ScrollPositionWithSingleContext.goBallistic] method. If the result
  /// is non-null, [ScrollPositionWithSingleContext] will begin a
  /// [BallisticScrollActivity] with the returned value. Otherwise, it will
  /// begin an idle activity instead.
  ///
  /// The given `position` is only valid during this method call. Do not keep a
  /// reference to it to use later, as the values may update, may not update, or
  /// may update to reflect an entirely unrelated scrollable.
369
  Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) {
370
    if (parent == null) {
371
      return null;
372
    }
373
    return parent!.createBallisticSimulation(position, velocity);
374 375
  }

376
  static final SpringDescription _kDefaultSpring = SpringDescription.withDampingRatio(
377
    mass: 0.5,
378
    stiffness: 100.0,
379 380 381
    ratio: 1.1,
  );

382
  /// The spring to use for ballistic simulations.
383 384 385
  SpringDescription get spring => parent?.spring ?? _kDefaultSpring;

  /// The default accuracy to which scrolling is computed.
386
  static final Tolerance _kDefaultTolerance = Tolerance(
387 388
    // TODO(ianh): Handle the case of the device pixel ratio changing.
    // TODO(ianh): Get this from the local MediaQuery not dart:ui's window object.
389 390
    velocity: 1.0 / (0.050 * WidgetsBinding.instance.window.devicePixelRatio), // logical pixels per second
    distance: 1.0 / WidgetsBinding.instance.window.devicePixelRatio, // logical pixels
391 392
  );

393
  /// The tolerance to use for ballistic simulations.
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
  Tolerance get tolerance => parent?.tolerance ?? _kDefaultTolerance;

  /// The minimum distance an input pointer drag must have moved to
  /// to be considered a scroll fling gesture.
  ///
  /// This value is typically compared with the distance traveled along the
  /// scrolling axis.
  ///
  /// See also:
  ///
  ///  * [VelocityTracker.getVelocityEstimate], which computes the velocity
  ///    of a press-drag-release gesture.
  double get minFlingDistance => parent?.minFlingDistance ?? kTouchSlop;

  /// The minimum velocity for an input pointer drag to be considered a
  /// scroll fling.
  ///
  /// This value is typically compared with the magnitude of fling gesture's
  /// velocity along the scrolling axis.
  ///
  /// See also:
  ///
  ///  * [VelocityTracker.getVelocityEstimate], which computes the velocity
  ///    of a press-drag-release gesture.
  double get minFlingVelocity => parent?.minFlingVelocity ?? kMinFlingVelocity;

  /// Scroll fling velocity magnitudes will be clamped to this value.
  double get maxFlingVelocity => parent?.maxFlingVelocity ?? kMaxFlingVelocity;

423 424 425 426 427 428 429
  /// Returns the velocity carried on repeated flings.
  ///
  /// The function is applied to the existing scroll velocity when another
  /// scroll drag is applied in the same direction.
  ///
  /// By default, physics for platforms other than iOS doesn't carry momentum.
  double carriedMomentum(double existingVelocity) {
430
    if (parent == null) {
431
      return 0.0;
432
    }
433
    return parent!.carriedMomentum(existingVelocity);
434 435
  }

436 437 438 439
  /// The minimum amount of pixel distance drags must move by to start motion
  /// the first time or after each time the drag motion stopped.
  ///
  /// If null, no minimum threshold is enforced.
440
  double? get dragStartDistanceMotionThreshold => parent?.dragStartDistanceMotionThreshold;
441

442
  /// Whether a viewport is allowed to change its scroll position implicitly in
443
  /// response to a call to [RenderObject.showOnScreen].
444 445 446 447 448 449 450
  ///
  /// [RenderObject.showOnScreen] is for example used to bring a text field
  /// fully on screen after it has received focus. This property controls
  /// whether the viewport associated with this object is allowed to change the
  /// scroll position to fulfill such a request.
  bool get allowImplicitScrolling => true;

451 452
  @override
  String toString() {
453
    if (parent == null) {
454
      return objectRuntimeType(this, 'ScrollPhysics');
455
    }
456
    return '${objectRuntimeType(this, 'ScrollPhysics')} -> $parent';
457 458
  }
}
459

460 461 462
/// Scroll physics that attempt to keep the scroll position in range when the
/// contents change dimensions suddenly.
///
463 464 465 466 467 468
/// This attempts to maintain the amount of overscroll or underscroll already present,
/// if the scroll position is already out of range _and_ the extents
/// have decreased, meaning that some content was removed. The reason for this
/// condition is that when new content is added, keeping the same overscroll
/// would mean that instead of showing it to the user, all of it is
/// being skipped by jumping right to the max extent.
469 470 471 472 473 474 475 476
///
/// If the scroll activity is animating the scroll position, sudden changes to
/// the scroll dimensions are allowed to happen (so as to prevent animations
/// from jumping back and forth between in-range and out-of-range values).
///
/// These physics should be combined with other scroll physics, e.g.
/// [BouncingScrollPhysics] or [ClampingScrollPhysics], to obtain a complete
/// description of typical scroll physics. See [applyTo].
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
///
/// ## Implementation details
///
/// Specifically, these physics perform two adjustments.
///
/// The first is to maintain overscroll when the position is out of range.
///
/// The second is to enforce the boundary when the position is in range.
///
/// If the current velocity is non-zero, neither adjustment is made. The
/// assumption is that there is an ongoing animation and therefore
/// further changing the scroll position would disrupt the experience.
///
/// If the extents haven't changed, then the overscroll adjustment is
/// not made. The assumption is that if the position is overscrolled,
/// it is intentional, otherwise the position could not have reached
/// that position. (Consider [ClampingScrollPhysics] vs
/// [BouncingScrollPhysics] for example.)
///
/// If the position itself changed since the last animation frame,
/// then the overscroll is not maintained. The assumption is similar
/// to the previous case: the position would not have been placed out
/// of range unless it was intentional.
///
/// In addition, if the position changed and the boundaries were and
/// still are finite, then the boundary isn't enforced either, for
/// the same reason. However, if any of the boundaries were or are
/// now infinite, the boundary _is_ enforced, on the assumption that
/// infinite boundaries indicate a lazy-loading scroll view, which
/// cannot enforce boundaries while the full list has not loaded.
///
/// If the range was out of range, then the boundary is not enforced
/// even if the range is not maintained. If the range is maintained,
/// then the distance between the old position and the old boundary is
/// applied to the new boundary to obtain the new position.
///
/// If the range was in range, and the boundary is to be enforced,
/// then the new position is obtained by deferring to the other physics,
/// if any, and then clamped to the new range.
516 517
class RangeMaintainingScrollPhysics extends ScrollPhysics {
  /// Creates scroll physics that maintain the scroll position in range.
518
  const RangeMaintainingScrollPhysics({ super.parent });
519 520

  @override
521
  RangeMaintainingScrollPhysics applyTo(ScrollPhysics? ancestor) {
522 523 524 525 526
    return RangeMaintainingScrollPhysics(parent: buildParent(ancestor));
  }

  @override
  double adjustPositionForNewDimensions({
527 528 529 530
    required ScrollMetrics oldPosition,
    required ScrollMetrics newPosition,
    required bool isScrolling,
    required double velocity,
531
  }) {
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
    bool maintainOverscroll = true;
    bool enforceBoundary = true;
    if (velocity != 0.0) {
      // Don't try to adjust an animating position, the jumping around
      // would be distracting.
      maintainOverscroll = false;
      enforceBoundary = false;
    }
    if ((oldPosition.minScrollExtent == newPosition.minScrollExtent) &&
        (oldPosition.maxScrollExtent == newPosition.maxScrollExtent)) {
      // If the extents haven't changed then ignore overscroll.
      maintainOverscroll = false;
    }
    if (oldPosition.pixels != newPosition.pixels) {
      // If the position has been changed already, then it might have
      // been adjusted to expect new overscroll, so don't try to
      // maintain the relative overscroll.
      maintainOverscroll = false;
      if (oldPosition.minScrollExtent.isFinite && oldPosition.maxScrollExtent.isFinite &&
          newPosition.minScrollExtent.isFinite && newPosition.maxScrollExtent.isFinite) {
552 553 554
        // In addition, if the position changed then we don't enforce the new
        // boundary if both the new and previous boundaries are entirely finite.
        // A common case where the position changes while one
555 556 557 558 559 560 561 562 563 564 565
        // of the extents is infinite is a lazily-loaded list. (If the
        // boundaries were finite, and the position changed, then we
        // assume it was intentional.)
        enforceBoundary = false;
      }
    }
    if ((oldPosition.pixels < oldPosition.minScrollExtent) ||
        (oldPosition.pixels > oldPosition.maxScrollExtent)) {
      // If the old position was out of range, then we should
      // not try to keep the new position in range.
      enforceBoundary = false;
566
    }
567
    if (maintainOverscroll) {
568 569 570 571 572 573 574 575
      // Force the new position to be no more out of range than it was before, if:
      //  * it was overscrolled, and
      //  * the extents have decreased, meaning that some content was removed. The
      //    reason for this condition is that when new content is added, keeping
      //    the same overscroll would mean that instead of showing it to the user,
      //    all of it is being skipped by jumping right to the max extent.
      if (oldPosition.pixels < oldPosition.minScrollExtent &&
          newPosition.minScrollExtent > oldPosition.minScrollExtent) {
576 577 578
        final double oldDelta = oldPosition.minScrollExtent - oldPosition.pixels;
        return newPosition.minScrollExtent - oldDelta;
      }
579 580
      if (oldPosition.pixels > oldPosition.maxScrollExtent &&
          newPosition.maxScrollExtent < oldPosition.maxScrollExtent) {
581 582 583
        final double oldDelta = oldPosition.pixels - oldPosition.maxScrollExtent;
        return newPosition.maxScrollExtent + oldDelta;
      }
584
    }
585 586 587 588
    // If we're not forcing the overscroll, defer to other physics.
    double result = super.adjustPositionForNewDimensions(oldPosition: oldPosition, newPosition: newPosition, isScrolling: isScrolling, velocity: velocity);
    if (enforceBoundary) {
      // ...but if they put us out of range then reinforce the boundary.
589
      result = clampDouble(result, newPosition.minScrollExtent, newPosition.maxScrollExtent);
590
    }
591
    return result;
592 593 594
  }
}

595 596 597 598 599 600
/// Scroll physics for environments that allow the scroll offset to go beyond
/// the bounds of the content, but then bounce the content back to the edge of
/// those bounds.
///
/// This is the behavior typically seen on iOS.
///
Kate Lovett's avatar
Kate Lovett committed
601 602 603 604 605 606 607
/// [BouncingScrollPhysics] by itself will not create an overscroll effect if
/// the contents of the scroll view do not extend beyond the size of the
/// viewport. To create the overscroll and bounce effect regardless of the
/// length of your scroll view, combine with [AlwaysScrollableScrollPhysics].
///
/// {@tool snippet}
/// ```dart
608
/// const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics())
Kate Lovett's avatar
Kate Lovett committed
609
/// ```
610
/// {@end-tool}
Kate Lovett's avatar
Kate Lovett committed
611
///
612 613
/// See also:
///
614
///  * [ScrollConfiguration], which uses this to provide the default
615
///    scroll behavior on iOS.
616 617
///  * [ClampingScrollPhysics], which is the analogous physics for Android's
///    clamping behavior.
Kate Lovett's avatar
Kate Lovett committed
618 619
///  * [ScrollPhysics], for more examples of combining [ScrollPhysics] objects
///    of different types to get the desired scroll physics.
620
class BouncingScrollPhysics extends ScrollPhysics {
621
  /// Creates scroll physics that bounce back from the edge.
622 623 624 625 626 627 628
  const BouncingScrollPhysics({
    this.decelerationRate = ScrollDecelerationRate.normal,
    super.parent,
  });

  /// Used to determine parameters for friction simulations.
  final ScrollDecelerationRate decelerationRate;
629 630

  @override
631
  BouncingScrollPhysics applyTo(ScrollPhysics? ancestor) {
632
    return BouncingScrollPhysics(parent: buildParent(ancestor));
633
  }
634 635 636

  /// The multiple applied to overscroll to make it appear that scrolling past
  /// the edge of the scrollable contents is harder than scrolling the list.
637 638
  /// This is done by reducing the ratio of the scroll effect output vs the
  /// scroll gesture input.
639
  ///
640
  /// This factor starts at 0.52 and progressively becomes harder to overscroll
641 642
  /// as more of the area past the edge is dragged in (represented by an increasing
  /// `overscrollFraction` which starts at 0 when there is no overscroll).
643 644 645 646 647 648 649 650
  double frictionFactor(double overscrollFraction) {
    switch (decelerationRate) {
      case ScrollDecelerationRate.fast:
        return 0.07 * math.pow(1 - overscrollFraction, 2);
      case ScrollDecelerationRate.normal:
        return 0.52 * math.pow(1 - overscrollFraction, 2);
    }
  }
651 652

  @override
653
  double applyPhysicsToUserOffset(ScrollMetrics position, double offset) {
654 655
    assert(offset != 0.0);
    assert(position.minScrollExtent <= position.maxScrollExtent);
656

657
    if (!position.outOfRange) {
658
      return offset;
659
    }
660 661 662

    final double overscrollPastStart = math.max(position.minScrollExtent - position.pixels, 0.0);
    final double overscrollPastEnd = math.max(position.pixels - position.maxScrollExtent, 0.0);
663
    final double overscrollPast = math.max(overscrollPastStart, overscrollPastEnd);
664 665 666 667 668
    final bool easing = (overscrollPastStart > 0.0 && offset < 0.0)
        || (overscrollPastEnd > 0.0 && offset > 0.0);

    final double friction = easing
        // Apply less resistance when easing the overscroll vs tensioning.
669 670
        ? frictionFactor((overscrollPast - offset.abs()) / position.viewportDimension)
        : frictionFactor(overscrollPast / position.viewportDimension);
671 672
    final double direction = offset.sign;

673
    return direction * _applyFriction(overscrollPast, offset.abs(), friction);
674 675
  }

676 677
  static double _applyFriction(double extentOutside, double absDelta, double gamma) {
    assert(absDelta > 0);
678
    double total = 0.0;
679 680
    if (extentOutside > 0) {
      final double deltaToLimit = extentOutside / gamma;
681
      if (absDelta < deltaToLimit) {
682
        return absDelta * gamma;
683
      }
684 685
      total += extentOutside;
      absDelta -= deltaToLimit;
686
    }
687
    return total + absDelta;
688 689
  }

690
  @override
691
  double applyBoundaryConditions(ScrollMetrics position, double value) => 0.0;
692

693
  @override
694
  Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) {
695 696
    final Tolerance tolerance = this.tolerance;
    if (velocity.abs() >= tolerance.velocity || position.outOfRange) {
697 698 699 700 701 702 703 704 705
      double constantDeceleration;
      switch (decelerationRate) {
        case ScrollDecelerationRate.fast:
          constantDeceleration = 1400;
          break;
        case ScrollDecelerationRate.normal:
          constantDeceleration = 0;
          break;
      }
706
      return BouncingScrollSimulation(
707 708
        spring: spring,
        position: position.pixels,
709
        velocity: velocity,
710 711
        leadingExtent: position.minScrollExtent,
        trailingExtent: position.maxScrollExtent,
712
        tolerance: tolerance,
713
        constantDeceleration: constantDeceleration
714
      );
715 716 717
    }
    return null;
  }
718 719 720 721 722 723

  // The ballistic simulation here decelerates more slowly than the one for
  // ClampingScrollPhysics so we require a more deliberate input gesture
  // to trigger a fling.
  @override
  double get minFlingVelocity => kMinFlingVelocity * 2.0;
724 725

  // Methodology:
726 727
  // 1- Use https://github.com/flutter/platform_tests/tree/master/scroll_overlay to test with
  //    Flutter and platform scroll views superimposed.
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
  // 3- If the scrollables stopped overlapping at any moment, adjust the desired
  //    output value of this function at that input speed.
  // 4- Feed new input/output set into a power curve fitter. Change function
  //    and repeat from 2.
  // 5- Repeat from 2 with medium and slow flings.
  /// Momentum build-up function that mimics iOS's scroll speed increase with repeated flings.
  ///
  /// The velocity of the last fling is not an important factor. Existing speed
  /// and (related) time since last fling are factors for the velocity transfer
  /// calculations.
  @override
  double carriedMomentum(double existingVelocity) {
    return existingVelocity.sign *
        math.min(0.000816 * math.pow(existingVelocity.abs(), 1.967).toDouble(), 40000.0);
  }
743

744 745
  // Eyeballed from observation to counter the effect of an unintended scroll
  // from the natural motion of lifting the finger after a scroll.
746
  @override
747
  double get dragStartDistanceMotionThreshold => 3.5;
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771

  @override
  double get maxFlingVelocity {
    switch (decelerationRate) {
      case ScrollDecelerationRate.fast:
        return kMaxFlingVelocity * 8.0;
      case ScrollDecelerationRate.normal:
        return super.maxFlingVelocity;
    }
  }

  @override
  SpringDescription get spring {
    switch (decelerationRate) {
      case ScrollDecelerationRate.fast:
        return SpringDescription.withDampingRatio(
          mass: 0.3,
          stiffness: 75.0,
          ratio: 1.3,
        );
      case ScrollDecelerationRate.normal:
        return super.spring;
    }
  }
772 773 774 775 776 777 778 779 780
}

/// Scroll physics for environments that prevent the scroll offset from reaching
/// beyond the bounds of the content.
///
/// This is the behavior typically seen on Android.
///
/// See also:
///
781
///  * [ScrollConfiguration], which uses this to provide the default
782
///    scroll behavior on Android.
783 784
///  * [BouncingScrollPhysics], which is the analogous physics for iOS' bouncing
///    behavior.
785
///  * [GlowingOverscrollIndicator], which is used by [ScrollConfiguration] to
786
///    provide the glowing effect that is usually found with this clamping effect
787
///    on Android. When using a [MaterialApp], the [GlowingOverscrollIndicator]'s
788 789
///    glow color is specified to use the overall theme's
///    [ColorScheme.secondary] color.
790
class ClampingScrollPhysics extends ScrollPhysics {
791
  /// Creates scroll physics that prevent the scroll offset from exceeding the
792
  /// bounds of the content.
793
  const ClampingScrollPhysics({ super.parent });
794 795

  @override
796
  ClampingScrollPhysics applyTo(ScrollPhysics? ancestor) {
797
    return ClampingScrollPhysics(parent: buildParent(ancestor));
798
  }
799 800

  @override
801 802 803
  double applyBoundaryConditions(ScrollMetrics position, double value) {
    assert(() {
      if (value == position.pixels) {
804 805 806 807 808 809
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('$runtimeType.applyBoundaryConditions() was called redundantly.'),
          ErrorDescription(
            'The proposed new position, $value, is exactly equal to the current position of the '
            'given ${position.runtimeType}, ${position.pixels}.\n'
            'The applyBoundaryConditions method should only be called when the value is '
810
            'going to actually change the pixels, otherwise it is redundant.',
811 812
          ),
          DiagnosticsProperty<ScrollPhysics>('The physics object in question was', this, style: DiagnosticsTreeStyle.errorProperty),
813
          DiagnosticsProperty<ScrollMetrics>('The position object in question was', position, style: DiagnosticsTreeStyle.errorProperty),
814
        ]);
815 816
      }
      return true;
817
    }());
818 819
    if (value < position.pixels && position.pixels <= position.minScrollExtent) {
      // Underscroll.
820
      return value - position.pixels;
821 822 823
    }
    if (position.maxScrollExtent <= position.pixels && position.pixels < value) {
      // Overscroll.
824
      return value - position.pixels;
825 826 827
    }
    if (value < position.minScrollExtent && position.minScrollExtent < position.pixels) {
      // Hit top edge.
828
      return value - position.minScrollExtent;
829 830 831
    }
    if (position.pixels < position.maxScrollExtent && position.maxScrollExtent < value) {
      // Hit bottom edge.
832
      return value - position.maxScrollExtent;
833
    }
834 835 836 837
    return 0.0;
  }

  @override
838
  Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) {
839 840
    final Tolerance tolerance = this.tolerance;
    if (position.outOfRange) {
841
      double? end;
842
      if (position.pixels > position.maxScrollExtent) {
843
        end = position.maxScrollExtent;
844 845
      }
      if (position.pixels < position.minScrollExtent) {
846
        end = position.minScrollExtent;
847
      }
848
      assert(end != null);
849
      return ScrollSpringSimulation(
850 851
        spring,
        position.pixels,
852
        end!,
853
        math.min(0.0, velocity),
854
        tolerance: tolerance,
855 856
      );
    }
857
    if (velocity.abs() < tolerance.velocity) {
858
      return null;
859 860
    }
    if (velocity > 0.0 && position.pixels >= position.maxScrollExtent) {
861
      return null;
862 863
    }
    if (velocity < 0.0 && position.pixels <= position.minScrollExtent) {
864
      return null;
865
    }
866
    return ClampingScrollSimulation(
867 868 869 870
      position: position.pixels,
      velocity: velocity,
      tolerance: tolerance,
    );
871 872 873
  }
}

874 875
/// Scroll physics that always lets the user scroll.
///
876 877 878 879
/// This overrides the default behavior which is to disable scrolling
/// when there is no content to scroll. It does not override the
/// handling of overscrolling.
///
880
/// On Android, overscrolls will be clamped by default and result in an
881 882
/// overscroll glow. On iOS, overscrolls will load a spring that will return the
/// scroll view to its normal range when released.
883 884 885
///
/// See also:
///
886 887
///  * [ScrollPhysics], which can be used instead of this class when the default
///    behavior is desired instead.
888 889 890 891
///  * [BouncingScrollPhysics], which provides the bouncing overscroll behavior
///    found on iOS.
///  * [ClampingScrollPhysics], which provides the clamping overscroll behavior
///    found on Android.
892
class AlwaysScrollableScrollPhysics extends ScrollPhysics {
893
  /// Creates scroll physics that always lets the user scroll.
894
  const AlwaysScrollableScrollPhysics({ super.parent });
895 896

  @override
897
  AlwaysScrollableScrollPhysics applyTo(ScrollPhysics? ancestor) {
898
    return AlwaysScrollableScrollPhysics(parent: buildParent(ancestor));
899 900
  }

901
  @override
902
  bool shouldAcceptUserOffset(ScrollMetrics position) => true;
903
}
904 905 906 907 908 909 910 911 912 913 914 915 916

/// Scroll physics that does not allow the user to scroll.
///
/// See also:
///
///  * [ScrollPhysics], which can be used instead of this class when the default
///    behavior is desired instead.
///  * [BouncingScrollPhysics], which provides the bouncing overscroll behavior
///    found on iOS.
///  * [ClampingScrollPhysics], which provides the clamping overscroll behavior
///    found on Android.
class NeverScrollableScrollPhysics extends ScrollPhysics {
  /// Creates scroll physics that does not let the user scroll.
917
  const NeverScrollableScrollPhysics({ super.parent });
918 919

  @override
920
  NeverScrollableScrollPhysics applyTo(ScrollPhysics? ancestor) {
921
    return NeverScrollableScrollPhysics(parent: buildParent(ancestor));
922 923 924 925
  }

  @override
  bool shouldAcceptUserOffset(ScrollMetrics position) => false;
926 927 928

  @override
  bool get allowImplicitScrolling => false;
929
}