scroll_configuration.dart 14.7 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
import 'package:flutter/foundation.dart';
6
import 'package:flutter/gestures.dart';
7
import 'package:flutter/rendering.dart';
8
import 'package:flutter/services.dart' show LogicalKeyboardKey;
9

10
import 'framework.dart';
11
import 'overscroll_indicator.dart';
12
import 'scroll_physics.dart';
13
import 'scrollable.dart';
14
import 'scrollable_helpers.dart';
15
import 'scrollbar.dart';
16

17
const Color _kDefaultGlowColor = Color(0xFFFFFFFF);
18

19 20 21 22 23
/// Device types that scrollables should accept drag gestures from by default.
const Set<PointerDeviceKind> _kTouchLikeDeviceTypes = <PointerDeviceKind>{
  PointerDeviceKind.touch,
  PointerDeviceKind.stylus,
  PointerDeviceKind.invertedStylus,
24
  PointerDeviceKind.trackpad,
25 26 27
  // The VoiceAccess sends pointer events with unknown type when scrolling
  // scrollables.
  PointerDeviceKind.unknown,
28 29
};

30 31 32 33 34 35 36
/// Types of overscroll indicators supported by [TargetPlatform.android].
enum AndroidOverscrollIndicator {
  /// Utilizes a [StretchingOverscrollIndicator], which transforms the contents
  /// of a [ScrollView] when overscrolled.
  stretch,

  /// Utilizes a [GlowingOverscrollIndicator], painting a glowing semi circle on
37
  /// top of the [ScrollView] in response to overscrolling.
38 39 40
  glow,
}

41 42
/// Describes how [Scrollable] widgets should behave.
///
43
/// {@template flutter.widgets.scrollBehavior}
44 45
/// Used by [ScrollConfiguration] to configure the [Scrollable] widgets in a
/// subtree.
46 47 48 49
///
/// This class can be extended to further customize a [ScrollBehavior] for a
/// subtree. For example, overriding [ScrollBehavior.getScrollPhysics] sets the
/// default [ScrollPhysics] for [Scrollable]s that inherit this [ScrollConfiguration].
50 51 52 53 54 55 56
/// Overriding [ScrollBehavior.buildOverscrollIndicator] can be used to add or change
/// the default [GlowingOverscrollIndicator] decoration, while
/// [ScrollBehavior.buildScrollbar] can be changed to modify the default [Scrollbar].
///
/// When looking to easily toggle the default decorations, you can use
/// [ScrollBehavior.copyWith] instead of creating your own [ScrollBehavior] class.
/// The `scrollbar` and `overscrollIndicator` flags can turn these decorations off.
57 58 59 60 61 62
/// {@endtemplate}
///
/// See also:
///
///   * [ScrollConfiguration], the inherited widget that controls how
///     [Scrollable] widgets behave in a subtree.
63
@immutable
Adam Barth's avatar
Adam Barth committed
64
class ScrollBehavior {
65
  /// Creates a description of how [Scrollable] widgets should behave.
66
  const ScrollBehavior();
67

68 69 70 71 72 73 74 75 76
  /// Creates a copy of this ScrollBehavior, making it possible to
  /// easily toggle `scrollbar` and `overscrollIndicator` effects.
  ///
  /// This is used by widgets like [PageView] and [ListWheelScrollView] to
  /// override the current [ScrollBehavior] and manage how they are decorated.
  /// Widgets such as these have the option to provide a [ScrollBehavior] on
  /// the widget level, like [PageView.scrollBehavior], in order to change the
  /// default.
  ScrollBehavior copyWith({
77 78
    bool? scrollbars,
    bool? overscroll,
79
    Set<PointerDeviceKind>? dragDevices,
80
    MultitouchDragStrategy? multitouchDragStrategy,
81
    Set<LogicalKeyboardKey>? pointerAxisModifiers,
82 83 84 85 86
    ScrollPhysics? physics,
    TargetPlatform? platform,
  }) {
    return _WrappedScrollBehavior(
      delegate: this,
87 88
      scrollbars: scrollbars ?? true,
      overscroll: overscroll ?? true,
89
      dragDevices: dragDevices,
90
      multitouchDragStrategy: multitouchDragStrategy,
91
      pointerAxisModifiers: pointerAxisModifiers,
92 93 94 95 96
      physics: physics,
      platform: platform,
    );
  }

97 98 99 100 101
  /// The platform whose scroll physics should be implemented.
  ///
  /// Defaults to the current platform.
  TargetPlatform getPlatform(BuildContext context) => defaultTargetPlatform;

102 103 104 105 106 107 108 109
  /// The device kinds that the scrollable will accept drag gestures from.
  ///
  /// By default only [PointerDeviceKind.touch], [PointerDeviceKind.stylus], and
  /// [PointerDeviceKind.invertedStylus] are configured to create drag gestures.
  /// Enabling this for [PointerDeviceKind.mouse] will make it difficult or
  /// impossible to select text in scrollable containers and is not recommended.
  Set<PointerDeviceKind> get dragDevices => _kTouchLikeDeviceTypes;

110 111 112 113 114 115
  /// {@macro flutter.gestures.monodrag.DragGestureRecognizer.multitouchDragStrategy}
  ///
  /// By default, [MultitouchDragStrategy.latestPointer] is configured to
  /// create drag gestures for all platforms.
  MultitouchDragStrategy get multitouchDragStrategy => MultitouchDragStrategy.latestPointer;

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
  /// A set of [LogicalKeyboardKey]s that, when any or all are pressed in
  /// combination with a [PointerDeviceKind.mouse] pointer scroll event, will
  /// flip the axes of the scroll input.
  ///
  /// This will for example, result in the input of a vertical mouse wheel, to
  /// move the [ScrollPosition] of a [ScrollView] with an [Axis.horizontal]
  /// scroll direction.
  ///
  /// If other keys exclusive of this set are pressed during a scroll event, in
  /// conjunction with keys from this set, the scroll input will still be
  /// flipped.
  ///
  /// Defaults to [LogicalKeyboardKey.shiftLeft],
  /// [LogicalKeyboardKey.shiftRight].
  Set<LogicalKeyboardKey> get pointerAxisModifiers => <LogicalKeyboardKey>{
    LogicalKeyboardKey.shiftLeft,
    LogicalKeyboardKey.shiftRight,
  };

135 136 137 138 139 140 141 142
  /// Applies a [RawScrollbar] to the child widget on desktop platforms.
  Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) {
    // When modifying this function, consider modifying the implementation in
    // the Material and Cupertino subclasses as well.
    switch (getPlatform(context)) {
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
143
        assert(details.controller != null);
144 145
        return RawScrollbar(
          controller: details.controller,
146
          child: child,
147
        );
148 149 150 151
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.iOS:
        return child;
152 153 154
    }
  }

155 156 157 158 159
  /// Applies a [GlowingOverscrollIndicator] to the child widget on
  /// [TargetPlatform.android] and [TargetPlatform.fuchsia].
  Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) {
    // When modifying this function, consider modifying the implementation in
    // the Material and Cupertino subclasses as well.
160 161 162 163 164 165 166 167
    switch (getPlatform(context)) {
      case TargetPlatform.iOS:
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
        return child;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
168 169 170 171 172
        return GlowingOverscrollIndicator(
          axisDirection: details.direction,
          color: _kDefaultGlowColor,
          child: child,
        );
173
    }
174 175
  }

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
  /// Specifies the type of velocity tracker to use in the descendant
  /// [Scrollable]s' drag gesture recognizers, for estimating the velocity of a
  /// drag gesture.
  ///
  /// This can be used to, for example, apply different fling velocity
  /// estimation methods on different platforms, in order to match the
  /// platform's native behavior.
  ///
  /// Typically, the provided [GestureVelocityTrackerBuilder] should return a
  /// fresh velocity tracker. If null is returned, [Scrollable] creates a new
  /// [VelocityTracker] to track the newly added pointer that may develop into
  /// a drag gesture.
  ///
  /// The default implementation provides a new
  /// [IOSScrollViewFlingVelocityTracker] on iOS and macOS for each new pointer,
  /// and a new [VelocityTracker] on other platforms for each new pointer.
  GestureVelocityTrackerBuilder velocityTrackerBuilder(BuildContext context) {
    switch (getPlatform(context)) {
      case TargetPlatform.iOS:
195
        return (PointerEvent event) => IOSScrollViewFlingVelocityTracker(event.kind);
196 197
      case TargetPlatform.macOS:
        return (PointerEvent event) => MacOSScrollViewFlingVelocityTracker(event.kind);
198 199 200 201
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
202
        return (PointerEvent event) => VelocityTracker.withKind(event.kind);
203 204 205
    }
  }

206
  static const ScrollPhysics _bouncingPhysics = BouncingScrollPhysics(parent: RangeMaintainingScrollPhysics());
207 208 209 210
  static const ScrollPhysics _bouncingDesktopPhysics = BouncingScrollPhysics(
    decelerationRate: ScrollDecelerationRate.fast,
    parent: RangeMaintainingScrollPhysics()
  );
211 212
  static const ScrollPhysics _clampingPhysics = ClampingScrollPhysics(parent: RangeMaintainingScrollPhysics());

213
  /// The scroll physics to use for the platform given by [getPlatform].
214
  ///
215 216
  /// Defaults to [RangeMaintainingScrollPhysics] mixed with
  /// [BouncingScrollPhysics] on iOS and [ClampingScrollPhysics] on
217
  /// Android.
218
  ScrollPhysics getScrollPhysics(BuildContext context) {
219 220
    // When modifying this function, consider modifying the implementation in
    // the Material and Cupertino subclasses as well.
221 222
    switch (getPlatform(context)) {
      case TargetPlatform.iOS:
223
        return _bouncingPhysics;
224 225
      case TargetPlatform.macOS:
        return _bouncingDesktopPhysics;
226 227
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
228 229
      case TargetPlatform.linux:
      case TargetPlatform.windows:
230
        return _clampingPhysics;
231 232 233
    }
  }

Adam Barth's avatar
Adam Barth committed
234 235 236 237 238 239 240 241 242 243
  /// Called whenever a [ScrollConfiguration] is rebuilt with a new
  /// [ScrollBehavior] of the same [runtimeType].
  ///
  /// If the new instance represents different information than the old
  /// instance, then the method should return true, otherwise it should return
  /// false.
  ///
  /// If this method returns true, all the widgets that inherit from the
  /// [ScrollConfiguration] will rebuild using the new [ScrollBehavior]. If this
  /// method returns false, the rebuilds might be optimized away.
244
  bool shouldNotify(covariant ScrollBehavior oldDelegate) => false;
245 246

  @override
247
  String toString() => objectRuntimeType(this, 'ScrollBehavior');
248 249
}

250 251 252
class _WrappedScrollBehavior implements ScrollBehavior {
  const _WrappedScrollBehavior({
    required this.delegate,
253 254
    this.scrollbars = true,
    this.overscroll = true,
255
    Set<PointerDeviceKind>? dragDevices,
256
    MultitouchDragStrategy? multitouchDragStrategy,
257
    Set<LogicalKeyboardKey>? pointerAxisModifiers,
258 259
    this.physics,
    this.platform,
260
  }) : _dragDevices = dragDevices,
261
        _multitouchDragStrategy = multitouchDragStrategy,
262
       _pointerAxisModifiers = pointerAxisModifiers;
263 264

  final ScrollBehavior delegate;
265 266
  final bool scrollbars;
  final bool overscroll;
267 268
  final ScrollPhysics? physics;
  final TargetPlatform? platform;
269
  final Set<PointerDeviceKind>? _dragDevices;
270
  final MultitouchDragStrategy? _multitouchDragStrategy;
271
  final Set<LogicalKeyboardKey>? _pointerAxisModifiers;
272 273 274

  @override
  Set<PointerDeviceKind> get dragDevices => _dragDevices ?? delegate.dragDevices;
275

276 277 278
  @override
  MultitouchDragStrategy get multitouchDragStrategy => _multitouchDragStrategy ?? delegate.multitouchDragStrategy;

279 280 281
  @override
  Set<LogicalKeyboardKey> get pointerAxisModifiers => _pointerAxisModifiers ?? delegate.pointerAxisModifiers;

282 283
  @override
  Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) {
284
    if (overscroll) {
285
      return delegate.buildOverscrollIndicator(context, child, details);
286
    }
287 288 289 290 291
    return child;
  }

  @override
  Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) {
292
    if (scrollbars) {
293
      return delegate.buildScrollbar(context, child, details);
294
    }
295 296 297 298 299
    return child;
  }

  @override
  ScrollBehavior copyWith({
300 301
    bool? scrollbars,
    bool? overscroll,
302
    Set<PointerDeviceKind>? dragDevices,
303
    MultitouchDragStrategy? multitouchDragStrategy,
304
    Set<LogicalKeyboardKey>? pointerAxisModifiers,
305 306 307 308
    ScrollPhysics? physics,
    TargetPlatform? platform,
  }) {
    return delegate.copyWith(
309 310
      scrollbars: scrollbars ?? this.scrollbars,
      overscroll: overscroll ?? this.overscroll,
311
      dragDevices: dragDevices ?? this.dragDevices,
312
      multitouchDragStrategy: multitouchDragStrategy ?? this.multitouchDragStrategy,
313
      pointerAxisModifiers: pointerAxisModifiers ?? this.pointerAxisModifiers,
314 315
      physics: physics ?? this.physics,
      platform: platform ?? this.platform,
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
    );
  }

  @override
  TargetPlatform getPlatform(BuildContext context) {
    return platform ?? delegate.getPlatform(context);
  }

  @override
  ScrollPhysics getScrollPhysics(BuildContext context) {
    return physics ?? delegate.getScrollPhysics(context);
  }

  @override
  bool shouldNotify(_WrappedScrollBehavior oldDelegate) {
    return oldDelegate.delegate.runtimeType != delegate.runtimeType
332 333
        || oldDelegate.scrollbars != scrollbars
        || oldDelegate.overscroll != overscroll
334
        || !setEquals<PointerDeviceKind>(oldDelegate.dragDevices, dragDevices)
335
        || oldDelegate.multitouchDragStrategy != multitouchDragStrategy
336
        || !setEquals<LogicalKeyboardKey>(oldDelegate.pointerAxisModifiers, pointerAxisModifiers)
337 338 339 340 341 342 343 344 345 346 347 348 349 350
        || oldDelegate.physics != physics
        || oldDelegate.platform != platform
        || delegate.shouldNotify(oldDelegate.delegate);
  }

  @override
  GestureVelocityTrackerBuilder velocityTrackerBuilder(BuildContext context) {
    return delegate.velocityTrackerBuilder(context);
  }

  @override
  String toString() => objectRuntimeType(this, '_WrappedScrollBehavior');
}

351 352 353
/// Controls how [Scrollable] widgets behave in a subtree.
///
/// The scroll configuration determines the [ScrollPhysics] and viewport
354
/// decorations used by descendants of [child].
Adam Barth's avatar
Adam Barth committed
355
class ScrollConfiguration extends InheritedWidget {
356
  /// Creates a widget that controls how [Scrollable] widgets behave in a subtree.
Adam Barth's avatar
Adam Barth committed
357
  const ScrollConfiguration({
358
    super.key,
359
    required this.behavior,
360 361
    required super.child,
  });
362

363
  /// How [Scrollable] widgets that are descendants of [child] should behave.
Adam Barth's avatar
Adam Barth committed
364
  final ScrollBehavior behavior;
365

366
  /// The [ScrollBehavior] for [Scrollable] widgets in the given [BuildContext].
367 368 369
  ///
  /// If no [ScrollConfiguration] widget is in scope of the given `context`,
  /// a default [ScrollBehavior] instance is returned.
Adam Barth's avatar
Adam Barth committed
370
  static ScrollBehavior of(BuildContext context) {
371
    final ScrollConfiguration? configuration = context.dependOnInheritedWidgetOfExactType<ScrollConfiguration>();
Adam Barth's avatar
Adam Barth committed
372
    return configuration?.behavior ?? const ScrollBehavior();
373 374 375
  }

  @override
Adam Barth's avatar
Adam Barth committed
376 377 378
  bool updateShouldNotify(ScrollConfiguration oldWidget) {
    return behavior.runtimeType != oldWidget.behavior.runtimeType
        || (behavior != oldWidget.behavior && behavior.shouldNotify(oldWidget.behavior));
379
  }
380 381

  @override
382 383
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
384
    properties.add(DiagnosticsProperty<ScrollBehavior>('behavior', behavior));
385
  }
386
}