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

5 6
import 'dart:math' as math;

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
import 'package:flutter/gestures.dart';
import 'package:flutter/physics.dart';
import 'package:flutter/rendering.dart';

import 'basic.dart';
import 'framework.dart';
import 'scroll_activity.dart';
import 'scroll_context.dart';
import 'scroll_notification.dart';
import 'scroll_physics.dart';
import 'scroll_position.dart';

/// A scroll position that manages scroll activities for a single
/// [ScrollContext].
///
/// This class is a concrete subclass of [ScrollPosition] logic that handles a
/// single [ScrollContext], such as a [Scrollable]. An instance of this class
/// manages [ScrollActivity] instances, which change what content is visible in
/// the [Scrollable]'s [Viewport].
///
/// See also:
///
///  * [ScrollPosition], which defines the underlying model for a position
30
///    within a [Scrollable] but is agnostic as to how that position is
31 32 33 34 35 36 37 38 39 40 41 42 43 44
///    changed.
///  * [ScrollView] and its subclasses such as [ListView], which use
///    [ScrollPositionWithSingleContext] to manage their scroll position.
///  * [ScrollController], which can manipulate one or more [ScrollPosition]s,
///    and which uses [ScrollPositionWithSingleContext] as its default class for
///    scroll positions.
class ScrollPositionWithSingleContext extends ScrollPosition implements ScrollActivityDelegate {
  /// Create a [ScrollPosition] object that manages its behavior using
  /// [ScrollActivity] objects.
  ///
  /// The `initialPixels` argument can be null, but in that case it is
  /// imperative that the value be set, using [correctPixels], as soon as
  /// [applyNewDimensions] is invoked, before calling the inherited
  /// implementation of that method.
45 46 47 48
  ///
  /// If [keepScrollOffset] is true (the default), the current scroll offset is
  /// saved with [PageStorage] and restored it if this scroll position's scrollable
  /// is recreated.
49
  ScrollPositionWithSingleContext({
50 51
    required super.physics,
    required super.context,
52
    double? initialPixels = 0.0,
53 54 55 56
    super.keepScrollOffset,
    super.oldPosition,
    super.debugLabel,
  }) {
57 58
    // If oldPosition is not null, the superclass will first call absorb(),
    // which may set _pixels and _activity.
59
    if (!hasPixels && initialPixels != null)
60 61 62 63 64 65
      correctPixels(initialPixels);
    if (activity == null)
      goIdle();
    assert(activity != null);
  }

66 67 68 69
  /// Velocity from a previous activity temporarily held by [hold] to potentially
  /// transfer to a next activity.
  double _heldPreviousVelocity = 0.0;

70 71 72 73 74
  @override
  AxisDirection get axisDirection => context.axisDirection;

  @override
  double setPixels(double newPixels) {
75
    assert(activity!.isScrolling);
76 77 78 79
    return super.setPixels(newPixels);
  }

  @override
80 81 82
  void absorb(ScrollPosition other) {
    super.absorb(other);
    if (other is! ScrollPositionWithSingleContext) {
83 84 85
      goIdle();
      return;
    }
86 87
    activity!.updateDelegate(this);
    _userScrollDirection = other._userScrollDirection;
88
    assert(_currentDrag == null);
89 90 91 92
    if (other._currentDrag != null) {
      _currentDrag = other._currentDrag;
      _currentDrag!.updateDelegate(this);
      other._currentDrag = null;
93
    }
94 95 96 97
  }

  @override
  void applyNewDimensions() {
98
    super.applyNewDimensions();
99 100 101
    context.setCanDrag(physics.shouldAcceptUserOffset(this));
  }

102
  @override
103
  void beginActivity(ScrollActivity? newActivity) {
104
    _heldPreviousVelocity = 0.0;
105 106 107
    if (newActivity == null)
      return;
    assert(newActivity.delegate == this);
108
    super.beginActivity(newActivity);
109 110
    _currentDrag?.dispose();
    _currentDrag = null;
111
    if (!activity!.isScrolling)
112 113 114 115
      updateUserScrollDirection(ScrollDirection.idle);
  }

  @override
116
  void applyUserOffset(double delta) {
117
    updateUserScrollDirection(delta > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse);
118
    setPixels(pixels - physics.applyPhysicsToUserOffset(this, delta));
119 120 121 122
  }

  @override
  void goIdle() {
123
    beginActivity(IdleScrollActivity(this));
124 125 126 127 128 129 130 131 132 133 134 135 136
  }

  /// Start a physics-driven simulation that settles the [pixels] position,
  /// starting at a particular velocity.
  ///
  /// This method defers to [ScrollPhysics.createBallisticSimulation], which
  /// typically provides a bounce simulation when the current position is out of
  /// bounds and a friction simulation when the position is in bounds but has a
  /// non-zero velocity.
  ///
  /// The velocity should be in logical pixels per second.
  @override
  void goBallistic(double velocity) {
137 138
    assert(hasPixels);
    final Simulation? simulation = physics.createBallisticSimulation(this, velocity);
139
    if (simulation != null) {
140
      beginActivity(BallisticScrollActivity(this, simulation, context.vsync));
141 142 143 144 145 146 147 148 149 150 151 152
    } else {
      goIdle();
    }
  }

  @override
  ScrollDirection get userScrollDirection => _userScrollDirection;
  ScrollDirection _userScrollDirection = ScrollDirection.idle;

  /// Set [userScrollDirection] to the given value.
  ///
  /// If this changes the value, then a [UserScrollNotification] is dispatched.
153
  @protected
154
  @visibleForTesting
155 156 157 158 159
  void updateUserScrollDirection(ScrollDirection value) {
    assert(value != null);
    if (userScrollDirection == value)
      return;
    _userScrollDirection = value;
160
    didUpdateScrollDirection(value);
161 162 163
  }

  @override
164 165
  Future<void> animateTo(
    double to, {
166 167
    required Duration duration,
    required Curve curve,
168
  }) {
169 170 171
    if (nearEqual(to, pixels, physics.tolerance.distance)) {
      // Skip the animation, go straight to the position as we are already close.
      jumpTo(to);
172
      return Future<void>.value();
173 174
    }

175
    final DrivenScrollActivity activity = DrivenScrollActivity(
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
      this,
      from: pixels,
      to: to,
      duration: duration,
      curve: curve,
      vsync: context.vsync,
    );
    beginActivity(activity);
    return activity.done;
  }

  @override
  void jumpTo(double value) {
    goIdle();
    if (pixels != value) {
      final double oldPixels = pixels;
      forcePixels(value);
193
      didStartScroll();
194
      didUpdateScrollPositionBy(pixels - oldPixels);
195
      didEndScroll();
196 197 198 199
    }
    goBallistic(0.0);
  }

200 201
  @override
  void pointerScroll(double delta) {
202 203 204
    // If an update is made to pointer scrolling here, consider if the same
    // (or similar) change should be made in
    // _NestedScrollCoordinator.pointerScroll.
205 206 207 208 209 210 211
    assert(delta != 0.0);

    final double targetPixels =
        math.min(math.max(pixels + delta, minScrollExtent), maxScrollExtent);
    if (targetPixels != pixels) {
      goIdle();
      updateUserScrollDirection(
212
          -delta > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse,
213 214 215
      );
      final double oldPixels = pixels;
      forcePixels(targetPixels);
216
      isScrollingNotifier.value = true;
217 218 219 220 221 222 223 224
      didStartScroll();
      didUpdateScrollPositionBy(pixels - oldPixels);
      didEndScroll();
      goBallistic(0.0);
    }
  }


225
  @Deprecated('This will lead to bugs.') // flutter_ignore: deprecation_syntax, https://github.com/flutter/flutter/issues/44609
226 227 228 229 230 231
  @override
  void jumpToWithoutSettling(double value) {
    goIdle();
    if (pixels != value) {
      final double oldPixels = pixels;
      forcePixels(value);
232
      didStartScroll();
233
      didUpdateScrollPositionBy(pixels - oldPixels);
234
      didEndScroll();
235 236 237 238
    }
  }

  @override
239
  ScrollHoldController hold(VoidCallback holdCancelCallback) {
240
    final double previousVelocity = activity!.velocity;
241
    final HoldScrollActivity holdActivity = HoldScrollActivity(
242 243 244
      delegate: this,
      onHoldCanceled: holdCancelCallback,
    );
245 246 247
    beginActivity(holdActivity);
    _heldPreviousVelocity = previousVelocity;
    return holdActivity;
248 249
  }

250
  ScrollDragController? _currentDrag;
251

252
  @override
253
  Drag drag(DragStartDetails details, VoidCallback dragCancelCallback) {
254
    final ScrollDragController drag = ScrollDragController(
255 256
      delegate: this,
      details: details,
257
      onDragCanceled: dragCancelCallback,
258
      carriedVelocity: physics.carriedMomentum(_heldPreviousVelocity),
259
      motionStartDistanceThreshold: physics.dragStartDistanceMotionThreshold,
260
    );
261
    beginActivity(DragScrollActivity(this, drag));
262 263 264
    assert(_currentDrag == null);
    _currentDrag = drag;
    return drag;
265 266 267 268
  }

  @override
  void dispose() {
269 270
    _currentDrag?.dispose();
    _currentDrag = null;
271 272 273 274 275 276 277 278 279 280 281 282
    super.dispose();
  }

  @override
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('${context.runtimeType}');
    description.add('$physics');
    description.add('$activity');
    description.add('$userScrollDirection');
  }
}