scroll_position_with_single_context.dart 8.89 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
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].
///
27 28
/// {@macro flutter.widgets.scrollPosition.listening}
///
29 30 31
/// See also:
///
///  * [ScrollPosition], which defines the underlying model for a position
32
///    within a [Scrollable] but is agnostic as to how that position is
33 34 35 36 37 38 39 40 41 42 43 44 45 46
///    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.
47 48 49 50
  ///
  /// 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.
51
  ScrollPositionWithSingleContext({
52 53
    required super.physics,
    required super.context,
54
    double? initialPixels = 0.0,
55 56 57 58
    super.keepScrollOffset,
    super.oldPosition,
    super.debugLabel,
  }) {
59 60
    // If oldPosition is not null, the superclass will first call absorb(),
    // which may set _pixels and _activity.
61
    if (!hasPixels && initialPixels != null) {
62
      correctPixels(initialPixels);
63 64
    }
    if (activity == null) {
65
      goIdle();
66
    }
67 68 69
    assert(activity != null);
  }

70 71 72 73
  /// Velocity from a previous activity temporarily held by [hold] to potentially
  /// transfer to a next activity.
  double _heldPreviousVelocity = 0.0;

74 75 76 77 78
  @override
  AxisDirection get axisDirection => context.axisDirection;

  @override
  double setPixels(double newPixels) {
79
    assert(activity!.isScrolling);
80 81 82 83
    return super.setPixels(newPixels);
  }

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

  @override
  void applyNewDimensions() {
102
    super.applyNewDimensions();
103 104 105
    context.setCanDrag(physics.shouldAcceptUserOffset(this));
  }

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

  @override
122
  void applyUserOffset(double delta) {
123
    updateUserScrollDirection(delta > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse);
124
    setPixels(pixels - physics.applyPhysicsToUserOffset(this, delta));
125 126 127 128
  }

  @override
  void goIdle() {
129
    beginActivity(IdleScrollActivity(this));
130 131 132 133 134 135 136 137 138 139 140 141 142
  }

  /// 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) {
143 144
    assert(hasPixels);
    final Simulation? simulation = physics.createBallisticSimulation(this, velocity);
145
    if (simulation != null) {
146 147 148 149 150 151
      beginActivity(BallisticScrollActivity(
        this,
        simulation,
        context.vsync,
        activity?.shouldIgnorePointer ?? true,
      ));
152 153 154 155 156 157 158 159 160 161 162 163
    } 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.
164
  @protected
165
  @visibleForTesting
166
  void updateUserScrollDirection(ScrollDirection value) {
167
    if (userScrollDirection == value) {
168
      return;
169
    }
170
    _userScrollDirection = value;
171
    didUpdateScrollDirection(value);
172 173 174
  }

  @override
175 176
  Future<void> animateTo(
    double to, {
177 178
    required Duration duration,
    required Curve curve,
179
  }) {
180
    if (nearEqual(to, pixels, physics.toleranceFor(this).distance)) {
181 182
      // Skip the animation, go straight to the position as we are already close.
      jumpTo(to);
183
      return Future<void>.value();
184 185
    }

186
    final DrivenScrollActivity activity = DrivenScrollActivity(
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
      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);
204
      didStartScroll();
205
      didUpdateScrollPositionBy(pixels - oldPixels);
206
      didEndScroll();
207 208 209 210
    }
    goBallistic(0.0);
  }

211 212
  @override
  void pointerScroll(double delta) {
213 214 215
    // If an update is made to pointer scrolling here, consider if the same
    // (or similar) change should be made in
    // _NestedScrollCoordinator.pointerScroll.
216 217 218 219
    if (delta == 0.0) {
      goBallistic(0.0);
      return;
    }
220 221 222 223 224 225

    final double targetPixels =
        math.min(math.max(pixels + delta, minScrollExtent), maxScrollExtent);
    if (targetPixels != pixels) {
      goIdle();
      updateUserScrollDirection(
226
          -delta > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse,
227 228
      );
      final double oldPixels = pixels;
229 230
      // Set the notifier before calling force pixels.
      // This is set to false again after going ballistic below.
231
      isScrollingNotifier.value = true;
232
      forcePixels(targetPixels);
233 234 235 236 237 238 239 240
      didStartScroll();
      didUpdateScrollPositionBy(pixels - oldPixels);
      didEndScroll();
      goBallistic(0.0);
    }
  }


241
  @Deprecated('This will lead to bugs.') // flutter_ignore: deprecation_syntax, https://github.com/flutter/flutter/issues/44609
242 243 244 245 246 247
  @override
  void jumpToWithoutSettling(double value) {
    goIdle();
    if (pixels != value) {
      final double oldPixels = pixels;
      forcePixels(value);
248
      didStartScroll();
249
      didUpdateScrollPositionBy(pixels - oldPixels);
250
      didEndScroll();
251 252 253 254
    }
  }

  @override
255
  ScrollHoldController hold(VoidCallback holdCancelCallback) {
256
    final double previousVelocity = activity!.velocity;
257
    final HoldScrollActivity holdActivity = HoldScrollActivity(
258 259 260
      delegate: this,
      onHoldCanceled: holdCancelCallback,
    );
261 262 263
    beginActivity(holdActivity);
    _heldPreviousVelocity = previousVelocity;
    return holdActivity;
264 265
  }

266
  ScrollDragController? _currentDrag;
267

268
  @override
269
  Drag drag(DragStartDetails details, VoidCallback dragCancelCallback) {
270
    final ScrollDragController drag = ScrollDragController(
271 272
      delegate: this,
      details: details,
273
      onDragCanceled: dragCancelCallback,
274
      carriedVelocity: physics.carriedMomentum(_heldPreviousVelocity),
275
      motionStartDistanceThreshold: physics.dragStartDistanceMotionThreshold,
276
    );
277
    beginActivity(DragScrollActivity(this, drag));
278 279 280
    assert(_currentDrag == null);
    _currentDrag = drag;
    return drag;
281 282 283 284
  }

  @override
  void dispose() {
285 286
    _currentDrag?.dispose();
    _currentDrag = null;
287 288 289 290 291 292 293 294 295 296 297 298
    super.dispose();
  }

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