scroll_position_with_single_context.dart 9.37 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
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';
15
import 'scroll_metrics.dart';
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
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
  ScrollPositionWithSingleContext({
51 52
    required super.physics,
    required super.context,
53
    double? initialPixels = 0.0,
54 55 56 57
    super.keepScrollOffset,
    super.oldPosition,
    super.debugLabel,
  }) {
58 59
    // If oldPosition is not null, the superclass will first call absorb(),
    // which may set _pixels and _activity.
60
    if (!hasPixels && initialPixels != null) {
61
      correctPixels(initialPixels);
62 63
    }
    if (activity == null) {
64
      goIdle();
65
    }
66 67 68
    assert(activity != null);
  }

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

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

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

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

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

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

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

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

  /// 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) {
142 143
    assert(hasPixels);
    final Simulation? simulation = physics.createBallisticSimulation(this, velocity);
144
    if (simulation != null) {
145 146 147 148 149 150 151 152
      beginActivity(BallisticScrollActivity(
        this,
        simulation,
        context.vsync,
        activity?.shouldIgnorePointer ?? true,
        initVelocity: velocity,
        initPosition: pixels,
      ));
153 154 155 156 157
    } else {
      goIdle();
    }
  }

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  @override
  Simulation? updateBallisticAnimation(double initVelocity, double initPosition) {
    assert(hasPixels);
    final FixedScrollMetrics initScrollMetrics = FixedScrollMetrics(
      minScrollExtent: minScrollExtent,
      maxScrollExtent: maxScrollExtent,
      pixels: initPosition,
      viewportDimension: viewportDimension,
      axisDirection: axisDirection,
    );
    final Simulation? simulation = physics.createBallisticSimulation(
      initScrollMetrics,
      initVelocity,
    );
    if (simulation == null) {
      goIdle();
      return null;
    }
    return simulation;
  }

179 180 181 182 183 184 185
  @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.
186
  @protected
187
  @visibleForTesting
188 189
  void updateUserScrollDirection(ScrollDirection value) {
    assert(value != null);
190
    if (userScrollDirection == value) {
191
      return;
192
    }
193
    _userScrollDirection = value;
194
    didUpdateScrollDirection(value);
195 196 197
  }

  @override
198 199
  Future<void> animateTo(
    double to, {
200 201
    required Duration duration,
    required Curve curve,
202
  }) {
203 204 205
    if (nearEqual(to, pixels, physics.tolerance.distance)) {
      // Skip the animation, go straight to the position as we are already close.
      jumpTo(to);
206
      return Future<void>.value();
207 208
    }

209
    final DrivenScrollActivity activity = DrivenScrollActivity(
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
      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);
227
      didStartScroll();
228
      didUpdateScrollPositionBy(pixels - oldPixels);
229
      didEndScroll();
230 231 232 233
    }
    goBallistic(0.0);
  }

234 235
  @override
  void pointerScroll(double delta) {
236 237 238
    // If an update is made to pointer scrolling here, consider if the same
    // (or similar) change should be made in
    // _NestedScrollCoordinator.pointerScroll.
239 240 241 242 243 244 245
    assert(delta != 0.0);

    final double targetPixels =
        math.min(math.max(pixels + delta, minScrollExtent), maxScrollExtent);
    if (targetPixels != pixels) {
      goIdle();
      updateUserScrollDirection(
246
          -delta > 0.0 ? ScrollDirection.forward : ScrollDirection.reverse,
247 248 249
      );
      final double oldPixels = pixels;
      forcePixels(targetPixels);
250
      isScrollingNotifier.value = true;
251 252 253 254 255 256 257 258
      didStartScroll();
      didUpdateScrollPositionBy(pixels - oldPixels);
      didEndScroll();
      goBallistic(0.0);
    }
  }


259
  @Deprecated('This will lead to bugs.') // flutter_ignore: deprecation_syntax, https://github.com/flutter/flutter/issues/44609
260 261 262 263 264 265
  @override
  void jumpToWithoutSettling(double value) {
    goIdle();
    if (pixels != value) {
      final double oldPixels = pixels;
      forcePixels(value);
266
      didStartScroll();
267
      didUpdateScrollPositionBy(pixels - oldPixels);
268
      didEndScroll();
269 270 271 272
    }
  }

  @override
273
  ScrollHoldController hold(VoidCallback holdCancelCallback) {
274
    final double previousVelocity = activity!.velocity;
275
    final HoldScrollActivity holdActivity = HoldScrollActivity(
276 277 278
      delegate: this,
      onHoldCanceled: holdCancelCallback,
    );
279 280 281
    beginActivity(holdActivity);
    _heldPreviousVelocity = previousVelocity;
    return holdActivity;
282 283
  }

284
  ScrollDragController? _currentDrag;
285

286
  @override
287
  Drag drag(DragStartDetails details, VoidCallback dragCancelCallback) {
288
    final ScrollDragController drag = ScrollDragController(
289 290
      delegate: this,
      details: details,
291
      onDragCanceled: dragCancelCallback,
292
      carriedVelocity: physics.carriedMomentum(_heldPreviousVelocity),
293
      motionStartDistanceThreshold: physics.dragStartDistanceMotionThreshold,
294
    );
295
    beginActivity(DragScrollActivity(this, drag));
296 297 298
    assert(_currentDrag == null);
    _currentDrag = drag;
    return drag;
299 300 301 302
  }

  @override
  void dispose() {
303 304
    _currentDrag?.dispose();
    _currentDrag = null;
305 306 307 308 309 310 311 312 313 314 315 316
    super.dispose();
  }

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