scroll_position_with_single_context.dart 8.18 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:flutter/physics.dart';
import 'package:flutter/rendering.dart';

import 'basic.dart';
import 'framework.dart';
import 'gesture_detector.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
31
///    within a [Scrollable] but is agnostic as to how that position is
32 33 34 35 36 37 38 39 40 41 42 43 44 45
///    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.
46 47 48 49
  ///
  /// 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.
50 51
  ScrollPositionWithSingleContext({
    @required ScrollPhysics physics,
52
    @required ScrollContext context,
53 54
    double initialPixels = 0.0,
    bool keepScrollOffset = true,
55
    ScrollPosition oldPosition,
56
    String debugLabel,
57 58 59 60 61 62 63
  }) : super(
         physics: physics,
         context: context,
         keepScrollOffset: keepScrollOffset,
         oldPosition: oldPosition,
         debugLabel: debugLabel,
       ) {
64 65 66 67 68 69 70 71 72
    // If oldPosition is not null, the superclass will first call absorb(),
    // which may set _pixels and _activity.
    if (pixels == null && initialPixels != null)
      correctPixels(initialPixels);
    if (activity == null)
      goIdle();
    assert(activity != null);
  }

73 74 75 76
  /// Velocity from a previous activity temporarily held by [hold] to potentially
  /// transfer to a next activity.
  double _heldPreviousVelocity = 0.0;

77 78 79 80 81 82 83 84 85 86
  @override
  AxisDirection get axisDirection => context.axisDirection;

  @override
  double setPixels(double newPixels) {
    assert(activity.isScrolling);
    return super.setPixels(newPixels);
  }

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

  @override
  void applyNewDimensions() {
106
    super.applyNewDimensions();
107 108 109
    context.setCanDrag(physics.shouldAcceptUserOffset(this));
  }

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

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

  @override
  void goIdle() {
131
    beginActivity(IdleScrollActivity(this));
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
  }

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

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

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

208
  @Deprecated('This will lead to bugs.') // ignore: flutter_deprecation_syntax, https://github.com/flutter/flutter/issues/44609
209 210 211 212 213 214
  @override
  void jumpToWithoutSettling(double value) {
    goIdle();
    if (pixels != value) {
      final double oldPixels = pixels;
      forcePixels(value);
215
      didStartScroll();
216
      didUpdateScrollPositionBy(pixels - oldPixels);
217
      didEndScroll();
218 219 220 221
    }
  }

  @override
222
  ScrollHoldController hold(VoidCallback holdCancelCallback) {
223
    final double previousVelocity = activity.velocity;
224
    final HoldScrollActivity holdActivity = HoldScrollActivity(
225 226 227
      delegate: this,
      onHoldCanceled: holdCancelCallback,
    );
228 229 230
    beginActivity(holdActivity);
    _heldPreviousVelocity = previousVelocity;
    return holdActivity;
231 232
  }

233 234
  ScrollDragController _currentDrag;

235
  @override
236
  Drag drag(DragStartDetails details, VoidCallback dragCancelCallback) {
237
    final ScrollDragController drag = ScrollDragController(
238 239
      delegate: this,
      details: details,
240
      onDragCanceled: dragCancelCallback,
241
      carriedVelocity: physics.carriedMomentum(_heldPreviousVelocity),
242
      motionStartDistanceThreshold: physics.dragStartDistanceMotionThreshold,
243
    );
244
    beginActivity(DragScrollActivity(this, drag));
245 246 247
    assert(_currentDrag == null);
    _currentDrag = drag;
    return drag;
248 249 250 251
  }

  @override
  void dispose() {
252 253
    _currentDrag?.dispose();
    _currentDrag = null;
254 255 256 257 258 259 260 261 262 263 264 265
    super.dispose();
  }

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