scroll_configuration.dart 15 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

9
import 'framework.dart';
10
import 'overscroll_indicator.dart';
11
import 'scroll_physics.dart';
12 13
import 'scrollable.dart';
import 'scrollbar.dart';
14

15
const Color _kDefaultGlowColor = Color(0xFFFFFFFF);
16

17 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 25 26 27 28 29 30 31 32 33 34
/// 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
35
  /// top of the [ScrollView] in response to overscrolling.
36 37 38
  glow,
}

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

72 73 74 75 76 77 78 79
  /// 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].
80 81 82 83
  @Deprecated(
    'Use ThemeData.useMaterial3 or override ScrollBehavior.buildOverscrollIndicator. '
    'This feature was deprecated after v2.13.0-0.0.pre.'
  )
84 85
  AndroidOverscrollIndicator get androidOverscrollIndicator => _androidOverscrollIndicator ?? _kDefaultAndroidOverscrollIndicator;
  final AndroidOverscrollIndicator? _androidOverscrollIndicator;
86

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

118 119 120 121 122
  /// The platform whose scroll physics should be implemented.
  ///
  /// Defaults to the current platform.
  TargetPlatform getPlatform(BuildContext context) => defaultTargetPlatform;

123 124 125 126 127 128 129 130
  /// 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;

131
  /// Wraps the given widget, which scrolls in the given [AxisDirection].
132
  ///
133 134 135
  /// For example, on Android, this method wraps the given widget with a
  /// [GlowingOverscrollIndicator] to provide visual feedback when the user
  /// overscrolls.
136 137 138 139 140
  ///
  /// This method is deprecated. Use [ScrollBehavior.buildOverscrollIndicator]
  /// instead.
  @Deprecated(
    'Migrate to buildOverscrollIndicator. '
141
    'This feature was deprecated after v2.1.0-11.0.pre.',
142
  )
143 144 145
  Widget buildViewportChrome(BuildContext context, Widget child, AxisDirection axisDirection) {
    switch (getPlatform(context)) {
      case TargetPlatform.iOS:
146
      case TargetPlatform.linux:
147
      case TargetPlatform.macOS:
148
      case TargetPlatform.windows:
149 150
        return child;
      case TargetPlatform.android:
151 152 153 154 155 156 157 158 159 160
        switch (androidOverscrollIndicator) {
          case AndroidOverscrollIndicator.stretch:
            return StretchingOverscrollIndicator(
              axisDirection: axisDirection,
              child: child,
            );
          case AndroidOverscrollIndicator.glow:
            continue glow;
        }
      glow:
161
      case TargetPlatform.fuchsia:
162 163 164
      return GlowingOverscrollIndicator(
        axisDirection: axisDirection,
        color: _kDefaultGlowColor,
165
        child: child,
166 167 168 169 170 171 172 173 174 175 176 177 178 179
      );
    }
  }

  /// 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:
        return RawScrollbar(
          controller: details.controller,
180
          child: child,
181
        );
182 183 184 185
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.iOS:
        return child;
186 187 188
    }
  }

189 190 191 192 193 194 195 196 197 198
  /// Applies a [GlowingOverscrollIndicator] to the child widget on
  /// [TargetPlatform.android] and [TargetPlatform.fuchsia].
  Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) {
    // TODO(Piinks): Move implementation from buildViewportChrome here after
    //  deprecation period
    // When modifying this function, consider modifying the implementation in
    // the Material and Cupertino subclasses as well.
    return buildViewportChrome(context, child, details.direction);
  }

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
  /// 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:
      case TargetPlatform.macOS:
219
        return (PointerEvent event) => IOSScrollViewFlingVelocityTracker(event.kind);
220 221 222 223
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
      case TargetPlatform.linux:
      case TargetPlatform.windows:
224
        return (PointerEvent event) => VelocityTracker.withKind(event.kind);
225 226 227
    }
  }

228 229 230
  static const ScrollPhysics _bouncingPhysics = BouncingScrollPhysics(parent: RangeMaintainingScrollPhysics());
  static const ScrollPhysics _clampingPhysics = ClampingScrollPhysics(parent: RangeMaintainingScrollPhysics());

231
  /// The scroll physics to use for the platform given by [getPlatform].
232
  ///
233 234
  /// Defaults to [RangeMaintainingScrollPhysics] mixed with
  /// [BouncingScrollPhysics] on iOS and [ClampingScrollPhysics] on
235
  /// Android.
236 237 238
  ScrollPhysics getScrollPhysics(BuildContext context) {
    switch (getPlatform(context)) {
      case TargetPlatform.iOS:
239
      case TargetPlatform.macOS:
240
        return _bouncingPhysics;
241 242
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
243 244
      case TargetPlatform.linux:
      case TargetPlatform.windows:
245
        return _clampingPhysics;
246 247 248
    }
  }

Adam Barth's avatar
Adam Barth committed
249 250 251 252 253 254 255 256 257 258
  /// 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.
259
  bool shouldNotify(covariant ScrollBehavior oldDelegate) => false;
260 261

  @override
262
  String toString() => objectRuntimeType(this, 'ScrollBehavior');
263 264
}

265 266 267
class _WrappedScrollBehavior implements ScrollBehavior {
  const _WrappedScrollBehavior({
    required this.delegate,
268 269
    this.scrollbars = true,
    this.overscroll = true,
270 271
    this.physics,
    this.platform,
272
    Set<PointerDeviceKind>? dragDevices,
273 274 275
    AndroidOverscrollIndicator? androidOverscrollIndicator,
  }) : _androidOverscrollIndicator = androidOverscrollIndicator,
       _dragDevices = dragDevices;
276 277

  final ScrollBehavior delegate;
278 279
  final bool scrollbars;
  final bool overscroll;
280 281
  final ScrollPhysics? physics;
  final TargetPlatform? platform;
282
  final Set<PointerDeviceKind>? _dragDevices;
283 284
  @override
  final AndroidOverscrollIndicator? _androidOverscrollIndicator;
285 286 287

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

289
  @override
290
  AndroidOverscrollIndicator get androidOverscrollIndicator => _androidOverscrollIndicator ?? delegate.androidOverscrollIndicator;
291

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

  @override
  Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) {
301
    if (scrollbars)
302 303 304 305 306 307 308 309 310 311 312
      return delegate.buildScrollbar(context, child, details);
    return child;
  }

  @override
  Widget buildViewportChrome(BuildContext context, Widget child, AxisDirection axisDirection) {
    return delegate.buildViewportChrome(context, child, axisDirection);
  }

  @override
  ScrollBehavior copyWith({
313 314
    bool? scrollbars,
    bool? overscroll,
315 316
    ScrollPhysics? physics,
    TargetPlatform? platform,
317
    Set<PointerDeviceKind>? dragDevices,
318
    AndroidOverscrollIndicator? androidOverscrollIndicator
319 320
  }) {
    return delegate.copyWith(
321 322 323 324 325 326
      scrollbars: scrollbars ?? this.scrollbars,
      overscroll: overscroll ?? this.overscroll,
      physics: physics ?? this.physics,
      platform: platform ?? this.platform,
      dragDevices: dragDevices ?? this.dragDevices,
      androidOverscrollIndicator: androidOverscrollIndicator ?? this.androidOverscrollIndicator,
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    );
  }

  @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
343 344
        || oldDelegate.scrollbars != scrollbars
        || oldDelegate.overscroll != overscroll
345 346
        || oldDelegate.physics != physics
        || oldDelegate.platform != platform
347
        || setEquals<PointerDeviceKind>(oldDelegate.dragDevices, dragDevices)
348 349 350 351 352 353 354 355 356 357 358 359
        || delegate.shouldNotify(oldDelegate.delegate);
  }

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

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

360 361 362
/// Controls how [Scrollable] widgets behave in a subtree.
///
/// The scroll configuration determines the [ScrollPhysics] and viewport
363
/// decorations used by descendants of [child].
Adam Barth's avatar
Adam Barth committed
364
class ScrollConfiguration extends InheritedWidget {
365 366 367
  /// 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
368
  const ScrollConfiguration({
369 370 371
    Key? key,
    required this.behavior,
    required Widget child,
372 373
  }) : super(key: key, child: child);

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

377
  /// The [ScrollBehavior] for [Scrollable] widgets in the given [BuildContext].
378 379 380
  ///
  /// If no [ScrollConfiguration] widget is in scope of the given `context`,
  /// a default [ScrollBehavior] instance is returned.
Adam Barth's avatar
Adam Barth committed
381
  static ScrollBehavior of(BuildContext context) {
382
    final ScrollConfiguration? configuration = context.dependOnInheritedWidgetOfExactType<ScrollConfiguration>();
Adam Barth's avatar
Adam Barth committed
383
    return configuration?.behavior ?? const ScrollBehavior();
384 385 386
  }

  @override
Adam Barth's avatar
Adam Barth committed
387
  bool updateShouldNotify(ScrollConfiguration oldWidget) {
388
    assert(behavior != null);
Adam Barth's avatar
Adam Barth committed
389 390
    return behavior.runtimeType != oldWidget.behavior.runtimeType
        || (behavior != oldWidget.behavior && behavior.shouldNotify(oldWidget.behavior));
391
  }
392 393

  @override
394 395
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
396
    properties.add(DiagnosticsProperty<ScrollBehavior>('behavior', behavior));
397
  }
398
}