scroll_position_with_single_context.dart 8.59 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 52
    required ScrollPhysics physics,
    required ScrollContext context,
    double? initialPixels = 0.0,
53
    bool keepScrollOffset = true,
54 55
    ScrollPosition? oldPosition,
    String? debugLabel,
56 57 58 59 60 61 62
  }) : super(
         physics: physics,
         context: context,
         keepScrollOffset: keepScrollOffset,
         oldPosition: oldPosition,
         debugLabel: debugLabel,
       ) {
63 64
    // If oldPosition is not null, the superclass will first call absorb(),
    // which may set _pixels and _activity.
65
    if (!hasPixels && initialPixels != null)
66 67 68 69 70 71
      correctPixels(initialPixels);
    if (activity == null)
      goIdle();
    assert(activity != null);
  }

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

76 77 78 79 80
  @override
  AxisDirection get axisDirection => context.axisDirection;

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

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

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

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

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

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

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

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
  @override
  void pointerScroll(double delta) {
    assert(delta != 0.0);

    final double targetPixels =
        math.min(math.max(pixels + delta, minScrollExtent), maxScrollExtent);
    if (targetPixels != pixels) {
      goIdle();
      updateUserScrollDirection(
          -delta > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse
      );
      final double oldPixels = pixels;
      forcePixels(targetPixels);
      didStartScroll();
      didUpdateScrollPositionBy(pixels - oldPixels);
      didEndScroll();
      goBallistic(0.0);
    }
  }


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

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

252
  ScrollDragController? _currentDrag;
253

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

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

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