scrollbar.dart 17.5 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/cupertino.dart';
6
import 'package:flutter/gestures.dart';
7

8 9
import 'color_scheme.dart';
import 'material_state.dart';
10
import 'scrollbar_theme.dart';
11 12
import 'theme.dart';

13 14 15 16 17
const double _kScrollbarThickness = 8.0;
const double _kScrollbarThicknessWithTrack = 12.0;
const double _kScrollbarMargin = 2.0;
const double _kScrollbarMinLength = 48.0;
const Radius _kScrollbarRadius = Radius.circular(8.0);
18 19
const Duration _kScrollbarFadeDuration = Duration(milliseconds: 300);
const Duration _kScrollbarTimeToFade = Duration(milliseconds: 600);
20

21
/// A Material Design scrollbar.
22
///
23
/// To add a scrollbar to a [ScrollView], wrap the scroll view
24 25
/// widget in a [Scrollbar] widget.
///
26 27
/// {@youtube 560 315 https://www.youtube.com/watch?v=DbkIQSvwnZc}
///
28
/// {@macro flutter.widgets.Scrollbar}
29
///
30 31
/// Dynamically changes to a [CupertinoScrollbar], an iOS style scrollbar, by
/// default on the iOS platform.
32
///
33 34 35 36
/// The color of the Scrollbar thumb will change when [MaterialState.dragged],
/// or [MaterialState.hovered] on desktop and web platforms. These stateful
/// color choices can be changed using [ScrollbarThemeData.thumbColor].
///
37
/// {@tool dartpad}
38 39 40
/// This sample shows a [Scrollbar] that executes a fade animation as scrolling
/// occurs. The Scrollbar will fade into view as the user scrolls, and fade out
/// when scrolling stops.
41 42
///
/// ** See code in examples/api/lib/material/scrollbar/scrollbar.0.dart **
43 44
/// {@end-tool}
///
45
/// {@tool dartpad}
46 47 48
/// When [thumbVisibility] is true, the scrollbar thumb will remain visible
/// without the fade animation. This requires that a [ScrollController] is
/// provided to controller, or that the [PrimaryScrollController] is available.
49
///
50
/// ** See code in examples/api/lib/material/scrollbar/scrollbar.1.dart **
51
/// {@end-tool}
52
///
53 54 55 56 57 58 59
/// A scrollbar track can be added using [trackVisibility]. This can also be
/// drawn when triggered by a hover event, or based on any [MaterialState] by
/// using [ScrollbarThemeData.trackVisibility].
///
/// The [thickness] of the track and scrollbar thumb can be changed dynamically
/// in response to [MaterialState]s using [ScrollbarThemeData.thickness].
///
60 61
/// See also:
///
62 63
///  * [RawScrollbar], a basic scrollbar that fades in and out, extended
///    by this class to add more animations and behaviors.
64
///  * [ScrollbarTheme], which configures the Scrollbar's appearance.
65 66 67
///  * [CupertinoScrollbar], an iOS style scrollbar.
///  * [ListView], which displays a linear, scrollable list of children.
///  * [GridView], which displays a 2 dimensional, scrollable array of children.
68
class Scrollbar extends StatelessWidget {
69 70
  /// Creates a material design scrollbar that by default will connect to the
  /// closest Scrollable descendant of [child].
71 72 73
  ///
  /// The [child] should be a source of [ScrollNotification] notifications,
  /// typically a [Scrollable] widget.
74 75 76 77
  ///
  /// If the [controller] is null, the default behavior is to
  /// enable scrollbar dragging using the [PrimaryScrollController].
  ///
78 79 80 81 82
  /// When null, [thickness] defaults to 8.0 pixels on desktop and web, and 4.0
  /// pixels when on mobile platforms. A null [radius] will result in a default
  /// of an 8.0 pixel circular radius about the corners of the scrollbar thumb,
  /// except for when executing on [TargetPlatform.android], which will render the
  /// thumb without a radius.
83
  const Scrollbar({
84 85 86
    Key? key,
    required this.child,
    this.controller,
87
    this.thumbVisibility,
88
    this.trackVisibility,
89 90
    this.thickness,
    this.radius,
91
    this.notificationPredicate,
92
    this.interactive,
93
    this.scrollbarOrientation,
94 95 96 97 98
    @Deprecated(
      'Use thumbVisibility instead. '
      'This feature was deprecated after v2.9.0-1.0.pre.',
    )
    this.isAlwaysShown,
99 100 101 102 103 104 105 106 107 108
    @Deprecated(
      'Use ScrollbarThemeData.trackVisibility to resolve based on the current state instead. '
      'This feature was deprecated after v2.9.0-1.0.pre.',
    )
    this.showTrackOnHover,
    @Deprecated(
      'Use ScrollbarThemeData.thickness to resolve based on the current state instead. '
      'This feature was deprecated after v2.9.0-1.0.pre.',
    )
    this.hoverThickness,
109 110 111 112 113 114
  }) : assert(
         thumbVisibility == null || isAlwaysShown == null,
         'Scrollbar thumb appearance should only be controlled with thumbVisibility, '
         'isAlwaysShown is deprecated.'
       ),
       super(key: key);
115 116 117 118 119 120 121

  /// {@macro flutter.widgets.Scrollbar.child}
  final Widget child;

  /// {@macro flutter.widgets.Scrollbar.controller}
  final ScrollController? controller;

122 123 124 125 126 127 128 129 130 131 132 133 134
  /// {@macro flutter.widgets.Scrollbar.thumbVisibility}
  ///
  /// If this property is null, then [ScrollbarThemeData.thumbVisibility] of
  /// [ThemeData.scrollbarTheme] is used. If that is also null, the default value
  /// is false.
  ///
  /// If the thumb visibility is related to the scrollbar's material state,
  /// use the global [ScrollbarThemeData.thumbVisibility] or override the
  /// sub-tree's theme data.
  ///
  /// Replaces deprecated [isAlwaysShown].
  final bool? thumbVisibility;

135
  /// {@macro flutter.widgets.Scrollbar.isAlwaysShown}
136 137 138 139 140 141 142
  ///
  /// To show the scrollbar thumb based on a [MaterialState], use
  /// [ScrollbarThemeData.thumbVisibility].
  @Deprecated(
    'Use thumbVisibility instead. '
    'This feature was deprecated after v2.9.0-1.0.pre.',
  )
143 144
  final bool? isAlwaysShown;

145 146 147 148 149 150 151 152 153 154
  /// Controls the track visibility.
  ///
  /// If this property is null, then [ScrollbarThemeData.trackVisibility] of
  /// [ThemeData.scrollbarTheme] is used. If that is also null, the default value
  /// is false.
  ///
  /// If the track visibility is related to the scrollbar's material state,
  /// use the global [ScrollbarThemeData.trackVisibility] or override the
  /// sub-tree's theme data.
  ///
155
  /// Replaces deprecated [showTrackOnHover].
156 157
  final bool? trackVisibility;

158 159 160 161 162
  /// Controls if the track will show on hover and remain, including during drag.
  ///
  /// If this property is null, then [ScrollbarThemeData.showTrackOnHover] of
  /// [ThemeData.scrollbarTheme] is used. If that is also null, the default value
  /// is false.
163
  ///
164 165 166 167 168 169
  /// This is deprecated, [trackVisibility] or [ScrollbarThemeData.trackVisibility]
  /// should be used instead.
  @Deprecated(
    'Use ScrollbarThemeData.trackVisibility to resolve based on the current state instead. '
    'This feature was deprecated after v2.9.0-1.0.pre.',
  )
170 171 172 173 174 175 176 177
  final bool? showTrackOnHover;

  /// The thickness of the scrollbar when a hover state is active and
  /// [showTrackOnHover] is true.
  ///
  /// If this property is null, then [ScrollbarThemeData.thickness] of
  /// [ThemeData.scrollbarTheme] is used to resolve a thickness. If that is also
  /// null, the default value is 12.0 pixels.
178 179 180 181 182 183 184
  ///
  /// This is deprecated, use [ScrollbarThemeData.thickness] to resolve based on
  /// the current state instead.
  @Deprecated(
    'Use ScrollbarThemeData.thickness to resolve based on the current state instead. '
    'This feature was deprecated after v2.9.0-1.0.pre.',
  )
185 186 187 188 189 190 191 192 193 194
  final double? hoverThickness;

  /// The thickness of the scrollbar in the cross axis of the scrollable.
  ///
  /// If null, the default value is platform dependent. On [TargetPlatform.android],
  /// the default thickness is 4.0 pixels. On [TargetPlatform.iOS],
  /// [CupertinoScrollbar.defaultThickness] is used. The remaining platforms have a
  /// default thickness of 8.0 pixels.
  final double? thickness;

195
  /// The [Radius] of the scrollbar thumb's rounded rectangle corners.
196 197 198 199 200 201 202
  ///
  /// If null, the default value is platform dependent. On [TargetPlatform.android],
  /// no radius is applied to the scrollbar thumb. On [TargetPlatform.iOS],
  /// [CupertinoScrollbar.defaultRadius] is used. The remaining platforms have a
  /// default [Radius.circular] of 8.0 pixels.
  final Radius? radius;

203 204 205
  /// {@macro flutter.widgets.Scrollbar.interactive}
  final bool? interactive;

206 207 208
  /// {@macro flutter.widgets.Scrollbar.notificationPredicate}
  final ScrollNotificationPredicate? notificationPredicate;

209 210 211
  /// {@macro flutter.widgets.Scrollbar.scrollbarOrientation}
  final ScrollbarOrientation? scrollbarOrientation;

212 213
  @override
  Widget build(BuildContext context) {
214
    if (Theme.of(context).platform == TargetPlatform.iOS) {
215
      return CupertinoScrollbar(
216
        thumbVisibility: isAlwaysShown ?? thumbVisibility ?? false,
217 218 219 220 221 222 223 224
        thickness: thickness ?? CupertinoScrollbar.defaultThickness,
        thicknessWhileDragging: thickness ?? CupertinoScrollbar.defaultThicknessWhileDragging,
        radius: radius ?? CupertinoScrollbar.defaultRadius,
        radiusWhileDragging: radius ?? CupertinoScrollbar.defaultRadiusWhileDragging,
        controller: controller,
        notificationPredicate: notificationPredicate,
        scrollbarOrientation: scrollbarOrientation,
        child: child,
225 226 227
      );
    }
    return _MaterialScrollbar(
228
      controller: controller,
229
      thumbVisibility: isAlwaysShown ?? thumbVisibility,
230
      trackVisibility: trackVisibility,
231 232 233 234 235 236 237 238
      showTrackOnHover: showTrackOnHover,
      hoverThickness: hoverThickness,
      thickness: thickness,
      radius: radius,
      notificationPredicate: notificationPredicate,
      interactive: interactive,
      scrollbarOrientation: scrollbarOrientation,
      child: child,
239 240 241 242 243 244
    );
  }
}

class _MaterialScrollbar extends RawScrollbar {
  const _MaterialScrollbar({
245
    Key? key,
246 247
    required Widget child,
    ScrollController? controller,
248
    bool? thumbVisibility,
249
    this.trackVisibility,
250
    this.showTrackOnHover,
251 252 253
    this.hoverThickness,
    double? thickness,
    Radius? radius,
254
    ScrollNotificationPredicate? notificationPredicate,
255
    bool? interactive,
256
    ScrollbarOrientation? scrollbarOrientation,
257 258 259 260
  }) : super(
         key: key,
         child: child,
         controller: controller,
261
         thumbVisibility: thumbVisibility,
262
         thickness: thickness,
263 264 265 266
         radius: radius,
         fadeDuration: _kScrollbarFadeDuration,
         timeToFade: _kScrollbarTimeToFade,
         pressDuration: Duration.zero,
267
         notificationPredicate: notificationPredicate ?? defaultScrollNotificationPredicate,
268
         interactive: interactive,
269
         scrollbarOrientation: scrollbarOrientation,
270 271
       );

272
  final bool? trackVisibility;
273
  final bool? showTrackOnHover;
274
  final double? hoverThickness;
275

276
  @override
277
  _MaterialScrollbarState createState() => _MaterialScrollbarState();
278 279
}

280
class _MaterialScrollbarState extends RawScrollbarState<_MaterialScrollbar> {
281 282 283 284
  late AnimationController _hoverAnimationController;
  bool _dragIsActive = false;
  bool _hoverIsActive = false;
  late ColorScheme _colorScheme;
285
  late ScrollbarThemeData _scrollbarTheme;
286 287
  // On Android, scrollbars should match native appearance.
  late bool _useAndroidScrollbar;
288

289
  @override
290
  bool get showScrollbar => widget.thumbVisibility ?? _scrollbarTheme.thumbVisibility?.resolve(_states) ?? _scrollbarTheme.isAlwaysShown ?? false;
291

292 293 294
  @override
  bool get enableGestures => widget.interactive ?? _scrollbarTheme.interactive ?? !_useAndroidScrollbar;

295 296
  bool get _showTrackOnHover => widget.showTrackOnHover ?? _scrollbarTheme.showTrackOnHover ?? false;

297 298 299 300 301 302 303
  MaterialStateProperty<bool> get _trackVisibility => MaterialStateProperty.resolveWith((Set<MaterialState> states) {
    if (states.contains(MaterialState.hovered) && _showTrackOnHover) {
      return true;
    }
    return widget.trackVisibility ?? _scrollbarTheme.trackVisibility?.resolve(states) ?? false;
  });

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
  Set<MaterialState> get _states => <MaterialState>{
    if (_dragIsActive) MaterialState.dragged,
    if (_hoverIsActive) MaterialState.hovered,
  };

  MaterialStateProperty<Color> get _thumbColor {
    final Color onSurface = _colorScheme.onSurface;
    final Brightness brightness = _colorScheme.brightness;
    late Color dragColor;
    late Color hoverColor;
    late Color idleColor;
    switch (brightness) {
      case Brightness.light:
        dragColor = onSurface.withOpacity(0.6);
        hoverColor = onSurface.withOpacity(0.5);
319 320 321
        idleColor = _useAndroidScrollbar
          ? Theme.of(context).highlightColor.withOpacity(1.0)
          : onSurface.withOpacity(0.1);
322
        break;
323 324 325
      case Brightness.dark:
        dragColor = onSurface.withOpacity(0.75);
        hoverColor = onSurface.withOpacity(0.65);
326 327 328
        idleColor = _useAndroidScrollbar
          ? Theme.of(context).highlightColor.withOpacity(1.0)
          : onSurface.withOpacity(0.3);
329
        break;
330
    }
331 332 333

    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
      if (states.contains(MaterialState.dragged))
334
        return _scrollbarTheme.thumbColor?.resolve(states) ?? dragColor;
335 336 337

      // If the track is visible, the thumb color hover animation is ignored and
      // changes immediately.
338
      if (_trackVisibility.resolve(states))
339
        return _scrollbarTheme.thumbColor?.resolve(states) ?? hoverColor;
340 341

      return Color.lerp(
342 343
        _scrollbarTheme.thumbColor?.resolve(states) ?? idleColor,
        _scrollbarTheme.thumbColor?.resolve(states) ?? hoverColor,
344 345 346
        _hoverAnimationController.value,
      )!;
    });
347 348
  }

349 350 351 352
  MaterialStateProperty<Color> get _trackColor {
    final Color onSurface = _colorScheme.onSurface;
    final Brightness brightness = _colorScheme.brightness;
    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
353
      if (_trackVisibility.resolve(states)) {
354 355 356 357
        return _scrollbarTheme.trackColor?.resolve(states)
          ?? (brightness == Brightness.light
            ? onSurface.withOpacity(0.03)
            : onSurface.withOpacity(0.05));
358
      }
359 360
      return const Color(0x00000000);
    });
361 362
  }

363 364 365 366
  MaterialStateProperty<Color> get _trackBorderColor {
    final Color onSurface = _colorScheme.onSurface;
    final Brightness brightness = _colorScheme.brightness;
    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
367
      if (_trackVisibility.resolve(states)) {
368 369 370 371
        return _scrollbarTheme.trackBorderColor?.resolve(states)
          ?? (brightness == Brightness.light
            ? onSurface.withOpacity(0.1)
            : onSurface.withOpacity(0.25));
372
      }
373
      return const Color(0x00000000);
374 375 376
    });
  }

377 378
  MaterialStateProperty<double> get _thickness {
    return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
379
      if (states.contains(MaterialState.hovered) && _trackVisibility.resolve(states))
380 381 382
        return widget.hoverThickness
          ?? _scrollbarTheme.thickness?.resolve(states)
          ?? _kScrollbarThicknessWithTrack;
383
      // The default scrollbar thickness is smaller on mobile.
384 385 386
      return widget.thickness
        ?? _scrollbarTheme.thickness?.resolve(states)
        ?? (_kScrollbarThickness / (_useAndroidScrollbar ? 2 : 1));
387 388 389 390 391 392 393 394 395
    });
  }

  @override
  void initState() {
    super.initState();
    _hoverAnimationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 200),
396
    );
397 398 399
    _hoverAnimationController.addListener(() {
      updateScrollbarPainter();
    });
400 401
  }

402 403 404
  @override
  void didChangeDependencies() {
    final ThemeData theme = Theme.of(context);
405 406
    _colorScheme = theme.colorScheme;
    _scrollbarTheme = theme.scrollbarTheme;
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
    switch (theme.platform) {
      case TargetPlatform.android:
        _useAndroidScrollbar = true;
        break;
      case TargetPlatform.iOS:
      case TargetPlatform.linux:
      case TargetPlatform.fuchsia:
      case TargetPlatform.macOS:
      case TargetPlatform.windows:
        _useAndroidScrollbar = false;
        break;
    }
    super.didChangeDependencies();
  }

422 423 424 425 426 427 428 429
  @override
  void updateScrollbarPainter() {
    scrollbarPainter
      ..color = _thumbColor.resolve(_states)
      ..trackColor = _trackColor.resolve(_states)
      ..trackBorderColor = _trackBorderColor.resolve(_states)
      ..textDirection = Directionality.of(context)
      ..thickness = _thickness.resolve(_states)
430 431 432 433
      ..radius = widget.radius ?? _scrollbarTheme.radius ?? (_useAndroidScrollbar ? null : _kScrollbarRadius)
      ..crossAxisMargin = _scrollbarTheme.crossAxisMargin ?? (_useAndroidScrollbar ? 0.0 : _kScrollbarMargin)
      ..mainAxisMargin = _scrollbarTheme.mainAxisMargin ?? 0.0
      ..minLength = _scrollbarTheme.minThumbLength ?? _kScrollbarMinLength
434
      ..padding = MediaQuery.of(context).padding
435 436
      ..scrollbarOrientation = widget.scrollbarOrientation
      ..ignorePointer = !enableGestures;
437
  }
438

439 440 441 442 443
  @override
  void handleThumbPressStart(Offset localPosition) {
    super.handleThumbPressStart(localPosition);
    setState(() { _dragIsActive = true; });
  }
444

445 446 447 448 449 450 451 452 453 454
  @override
  void handleThumbPressEnd(Offset localPosition, Velocity velocity) {
    super.handleThumbPressEnd(localPosition, velocity);
    setState(() { _dragIsActive = false; });
  }

  @override
  void handleHover(PointerHoverEvent event) {
    super.handleHover(event);
    // Check if the position of the pointer falls over the painted scrollbar
455
    if (isPointerOverScrollbar(event.position, event.kind, forHover: true)) {
456 457 458 459 460 461 462
      // Pointer is hovering over the scrollbar
      setState(() { _hoverIsActive = true; });
      _hoverAnimationController.forward();
    } else if (_hoverIsActive) {
      // Pointer was, but is no longer over painted scrollbar.
      setState(() { _hoverIsActive = false; });
      _hoverAnimationController.reverse();
463
    }
464 465
  }

466
  @override
467 468 469 470
  void handleHoverExit(PointerExitEvent event) {
    super.handleHoverExit(event);
    setState(() { _hoverIsActive = false; });
    _hoverAnimationController.reverse();
471 472
  }

473
  @override
474 475 476
  void dispose() {
    _hoverAnimationController.dispose();
    super.dispose();
477 478
  }
}