scroll_configuration.dart 16.1 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 37 38 39 40
/// The default overscroll indicator applied on [TargetPlatform.android].
// TODO(Piinks): Complete migration to stretch by default.
const AndroidOverscrollIndicator _kDefaultAndroidOverscrollIndicator = AndroidOverscrollIndicator.glow;

/// 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
41
  /// top of the [ScrollView] in response to overscrolling.
42 43 44
  glow,
}

45 46
/// Describes how [Scrollable] widgets should behave.
///
47
/// {@template flutter.widgets.scrollBehavior}
48 49
/// Used by [ScrollConfiguration] to configure the [Scrollable] widgets in a
/// subtree.
50 51 52 53
///
/// 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].
54 55 56 57 58 59 60
/// 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.
61 62 63 64 65 66
/// {@endtemplate}
///
/// See also:
///
///   * [ScrollConfiguration], the inherited widget that controls how
///     [Scrollable] widgets behave in a subtree.
67
@immutable
Adam Barth's avatar
Adam Barth committed
68
class ScrollBehavior {
69
  /// Creates a description of how [Scrollable] widgets should behave.
70
  const ScrollBehavior({
71 72 73 74
    @Deprecated(
      'Use ThemeData.useMaterial3 or override ScrollBehavior.buildOverscrollIndicator. '
      'This feature was deprecated after v2.13.0-0.0.pre.'
    )
75 76 77
    AndroidOverscrollIndicator? androidOverscrollIndicator,
  }): _androidOverscrollIndicator = androidOverscrollIndicator;

78 79 80 81 82 83 84 85
  /// Specifies which overscroll indicator to use on [TargetPlatform.android].
  ///
  /// Cannot be null. Defaults to [AndroidOverscrollIndicator.glow].
  ///
  /// See also:
  ///
  ///   * [MaterialScrollBehavior], which supports setting this property
  ///     using [ThemeData].
86 87 88 89
  @Deprecated(
    'Use ThemeData.useMaterial3 or override ScrollBehavior.buildOverscrollIndicator. '
    'This feature was deprecated after v2.13.0-0.0.pre.'
  )
90 91
  AndroidOverscrollIndicator get androidOverscrollIndicator => _androidOverscrollIndicator ?? _kDefaultAndroidOverscrollIndicator;
  final AndroidOverscrollIndicator? _androidOverscrollIndicator;
92

93 94 95 96 97 98 99 100 101
  /// 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({
102 103
    bool? scrollbars,
    bool? overscroll,
104
    Set<PointerDeviceKind>? dragDevices,
105
    Set<LogicalKeyboardKey>? pointerAxisModifiers,
106 107
    ScrollPhysics? physics,
    TargetPlatform? platform,
108 109 110 111
    @Deprecated(
      'Use ThemeData.useMaterial3 or override ScrollBehavior.buildOverscrollIndicator. '
      'This feature was deprecated after v2.13.0-0.0.pre.'
    )
112
    AndroidOverscrollIndicator? androidOverscrollIndicator,
113 114 115
  }) {
    return _WrappedScrollBehavior(
      delegate: this,
116 117
      scrollbars: scrollbars ?? true,
      overscroll: overscroll ?? true,
118 119
      dragDevices: dragDevices,
      pointerAxisModifiers: pointerAxisModifiers,
120 121
      physics: physics,
      platform: platform,
122
      androidOverscrollIndicator: androidOverscrollIndicator
123 124 125
    );
  }

126 127 128 129 130
  /// The platform whose scroll physics should be implemented.
  ///
  /// Defaults to the current platform.
  TargetPlatform getPlatform(BuildContext context) => defaultTargetPlatform;

131 132 133 134 135 136 137 138
  /// 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;

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  /// 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,
  };

158 159 160 161 162 163 164 165
  /// 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:
166
        assert(details.controller != null);
167 168
        return RawScrollbar(
          controller: details.controller,
169
          child: child,
170
        );
171 172 173 174
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.iOS:
        return child;
175 176 177
    }
  }

178 179 180 181 182
  /// 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.
183 184 185 186 187 188 189 190 191 192 193 194 195 196
    switch (getPlatform(context)) {
      case TargetPlatform.iOS:
      case TargetPlatform.linux:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
        return child;
      case TargetPlatform.android:
        switch (androidOverscrollIndicator) {
          case AndroidOverscrollIndicator.stretch:
            return StretchingOverscrollIndicator(
              axisDirection: details.direction,
              child: child,
            );
          case AndroidOverscrollIndicator.glow:
197
            break;
198 199
        }
      case TargetPlatform.fuchsia:
200
        break;
201
    }
202 203 204 205 206 207 208
    return GlowingOverscrollIndicator(
      axisDirection: details.direction,
      color: _kDefaultGlowColor,
      child: child,
    );
  }

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
  /// 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:
228
        return (PointerEvent event) => IOSScrollViewFlingVelocityTracker(event.kind);
229 230
      case TargetPlatform.macOS:
        return (PointerEvent event) => MacOSScrollViewFlingVelocityTracker(event.kind);
231 232 233 234
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
235
        return (PointerEvent event) => VelocityTracker.withKind(event.kind);
236 237 238
    }
  }

239
  static const ScrollPhysics _bouncingPhysics = BouncingScrollPhysics(parent: RangeMaintainingScrollPhysics());
240 241 242 243
  static const ScrollPhysics _bouncingDesktopPhysics = BouncingScrollPhysics(
    decelerationRate: ScrollDecelerationRate.fast,
    parent: RangeMaintainingScrollPhysics()
  );
244 245
  static const ScrollPhysics _clampingPhysics = ClampingScrollPhysics(parent: RangeMaintainingScrollPhysics());

246
  /// The scroll physics to use for the platform given by [getPlatform].
247
  ///
248 249
  /// Defaults to [RangeMaintainingScrollPhysics] mixed with
  /// [BouncingScrollPhysics] on iOS and [ClampingScrollPhysics] on
250
  /// Android.
251
  ScrollPhysics getScrollPhysics(BuildContext context) {
252 253
    // When modifying this function, consider modifying the implementation in
    // the Material and Cupertino subclasses as well.
254 255
    switch (getPlatform(context)) {
      case TargetPlatform.iOS:
256
        return _bouncingPhysics;
257 258
      case TargetPlatform.macOS:
        return _bouncingDesktopPhysics;
259 260
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
261 262
      case TargetPlatform.linux:
      case TargetPlatform.windows:
263
        return _clampingPhysics;
264 265 266
    }
  }

Adam Barth's avatar
Adam Barth committed
267 268 269 270 271 272 273 274 275 276
  /// 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.
277
  bool shouldNotify(covariant ScrollBehavior oldDelegate) => false;
278 279

  @override
280
  String toString() => objectRuntimeType(this, 'ScrollBehavior');
281 282
}

283 284 285
class _WrappedScrollBehavior implements ScrollBehavior {
  const _WrappedScrollBehavior({
    required this.delegate,
286 287
    this.scrollbars = true,
    this.overscroll = true,
288 289
    Set<PointerDeviceKind>? dragDevices,
    Set<LogicalKeyboardKey>? pointerAxisModifiers,
290 291
    this.physics,
    this.platform,
292 293
    AndroidOverscrollIndicator? androidOverscrollIndicator,
  }) : _androidOverscrollIndicator = androidOverscrollIndicator,
294 295
       _dragDevices = dragDevices,
       _pointerAxisModifiers = pointerAxisModifiers;
296 297

  final ScrollBehavior delegate;
298 299
  final bool scrollbars;
  final bool overscroll;
300 301
  final ScrollPhysics? physics;
  final TargetPlatform? platform;
302
  final Set<PointerDeviceKind>? _dragDevices;
303
  final Set<LogicalKeyboardKey>? _pointerAxisModifiers;
304 305
  @override
  final AndroidOverscrollIndicator? _androidOverscrollIndicator;
306 307 308

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

310 311 312
  @override
  Set<LogicalKeyboardKey> get pointerAxisModifiers => _pointerAxisModifiers ?? delegate.pointerAxisModifiers;

313
  @override
314
  AndroidOverscrollIndicator get androidOverscrollIndicator => _androidOverscrollIndicator ?? delegate.androidOverscrollIndicator;
315

316 317
  @override
  Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) {
318
    if (overscroll) {
319
      return delegate.buildOverscrollIndicator(context, child, details);
320
    }
321 322 323 324 325
    return child;
  }

  @override
  Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) {
326
    if (scrollbars) {
327
      return delegate.buildScrollbar(context, child, details);
328
    }
329 330 331 332 333
    return child;
  }

  @override
  ScrollBehavior copyWith({
334 335
    bool? scrollbars,
    bool? overscroll,
336 337
    Set<PointerDeviceKind>? dragDevices,
    Set<LogicalKeyboardKey>? pointerAxisModifiers,
338 339
    ScrollPhysics? physics,
    TargetPlatform? platform,
340
    AndroidOverscrollIndicator? androidOverscrollIndicator
341 342
  }) {
    return delegate.copyWith(
343 344
      scrollbars: scrollbars ?? this.scrollbars,
      overscroll: overscroll ?? this.overscroll,
345 346
      dragDevices: dragDevices ?? this.dragDevices,
      pointerAxisModifiers: pointerAxisModifiers ?? this.pointerAxisModifiers,
347 348 349
      physics: physics ?? this.physics,
      platform: platform ?? this.platform,
      androidOverscrollIndicator: androidOverscrollIndicator ?? this.androidOverscrollIndicator,
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
    );
  }

  @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
366 367
        || oldDelegate.scrollbars != scrollbars
        || oldDelegate.overscroll != overscroll
368 369
        || !setEquals<PointerDeviceKind>(oldDelegate.dragDevices, dragDevices)
        || !setEquals<LogicalKeyboardKey>(oldDelegate.pointerAxisModifiers, pointerAxisModifiers)
370 371 372 373 374 375 376 377 378 379 380 381 382 383
        || 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');
}

384 385 386
/// Controls how [Scrollable] widgets behave in a subtree.
///
/// The scroll configuration determines the [ScrollPhysics] and viewport
387
/// decorations used by descendants of [child].
Adam Barth's avatar
Adam Barth committed
388
class ScrollConfiguration extends InheritedWidget {
389 390 391
  /// Creates a widget that controls how [Scrollable] widgets behave in a subtree.
  ///
  /// The [behavior] and [child] arguments must not be null.
Adam Barth's avatar
Adam Barth committed
392
  const ScrollConfiguration({
393
    super.key,
394
    required this.behavior,
395 396
    required super.child,
  });
397

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

401
  /// The [ScrollBehavior] for [Scrollable] widgets in the given [BuildContext].
402 403 404
  ///
  /// If no [ScrollConfiguration] widget is in scope of the given `context`,
  /// a default [ScrollBehavior] instance is returned.
Adam Barth's avatar
Adam Barth committed
405
  static ScrollBehavior of(BuildContext context) {
406
    final ScrollConfiguration? configuration = context.dependOnInheritedWidgetOfExactType<ScrollConfiguration>();
Adam Barth's avatar
Adam Barth committed
407
    return configuration?.behavior ?? const ScrollBehavior();
408 409 410
  }

  @override
Adam Barth's avatar
Adam Barth committed
411 412 413
  bool updateShouldNotify(ScrollConfiguration oldWidget) {
    return behavior.runtimeType != oldWidget.behavior.runtimeType
        || (behavior != oldWidget.behavior && behavior.shouldNotify(oldWidget.behavior));
414
  }
415 416

  @override
417 418
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
419
    properties.add(DiagnosticsProperty<ScrollBehavior>('behavior', behavior));
420
  }
421
}