scroll_position_with_single_context.dart 8.83 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
      correctPixels(initialPixels);
61 62
    }
    if (activity == null) {
63
      goIdle();
64
    }
65 66 67
    assert(activity != null);
  }

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

72 73 74 75 76
  @override
  AxisDirection get axisDirection => context.axisDirection;

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

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

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

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

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

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

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

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

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

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

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


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

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

264
  ScrollDragController? _currentDrag;
265

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

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

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