slider.dart 53 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
// @dart = 2.8

7
import 'dart:async';
8 9
import 'dart:math' as math;

10
import 'package:flutter/cupertino.dart';
11
import 'package:flutter/foundation.dart';
12 13
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
14
import 'package:flutter/scheduler.dart' show timeDilation;
15
import 'package:flutter/services.dart';
16 17
import 'package:flutter/widgets.dart';

18
import 'constants.dart';
19
import 'debug.dart';
20
import 'material.dart';
21
import 'material_state.dart';
22
import 'slider_theme.dart';
23 24
import 'theme.dart';

25
// Examples can assume:
26
// int _dollars = 0;
27
// int _duelCommandment = 1;
28
// void setState(VoidCallback fn) { }
29

30 31 32 33 34 35
/// [Slider] uses this callback to paint the value indicator on the overlay.
///
/// Since the value indicator is painted on the Overlay; this method paints the
/// value indicator in a [RenderBox] that appears in the [Overlay].
typedef PaintValueIndicator = void Function(PaintingContext context, Offset offset);

36 37
enum _SliderType { material, adaptive }

38
/// A Material Design slider.
39
///
40 41
/// Used to select from a range of values.
///
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
/// {@tool dartpad --template=stateful_widget_scaffold}
///
/// ![A slider widget, consisting of 5 divisions and showing the default value
/// indicator.](https://flutter.github.io/assets-for-api-docs/assets/material/slider.png)
///
/// The Sliders value is part of the Stateful widget subclass to change the value
/// setState was called.
///
/// ```dart
/// double _currentSliderValue = 20;
///
/// @override
/// Widget build(BuildContext context) {
///   return Slider(
///     value: _currentSliderValue,
///     min: 0,
///     max: 100,
///     divisions: 5,
///     label: _currentSliderValue.round().toString(),
///     onChanged: (double value) {
///       setState(() {
///         _currentSliderValue = value;
///       });
///     },
///   );
/// }
/// ```
/// {@end-tool}
///
71
/// A slider can be used to select from either a continuous or a discrete set of
72 73
/// values. The default is to use a continuous range of values from [min] to
/// [max]. To use discrete values, use a non-null value for [divisions], which
74
/// indicates the number of discrete intervals. For example, if [min] is 0.0 and
75
/// [max] is 50.0 and [divisions] is 5, then the slider can take on the
76
/// discrete values 0.0, 10.0, 20.0, 30.0, 40.0, and 50.0.
77
///
78 79 80 81
/// The terms for the parts of a slider are:
///
///  * The "thumb", which is a shape that slides horizontally when the user
///    drags it.
82
///  * The "track", which is the line that the slider thumb slides along.
83 84 85 86 87 88 89
///  * The "value indicator", which is a shape that pops up when the user
///    is dragging the thumb to indicate the value being selected.
///  * The "active" side of the slider is the side between the thumb and the
///    minimum value.
///  * The "inactive" side of the slider is the side between the thumb and the
///    maximum value.
///
90 91 92
/// The slider will be disabled if [onChanged] is null or if the range given by
/// [min]..[max] is empty (i.e. if [min] is equal to [max]).
///
93 94 95 96
/// The slider widget itself does not maintain any state. Instead, when the state
/// of the slider changes, the widget calls the [onChanged] callback. Most
/// widgets that use a slider will listen for the [onChanged] callback and
/// rebuild the slider with a new [value] to update the visual appearance of the
97 98
/// slider. To know when the value starts to change, or when it is done
/// changing, set the optional callbacks [onChangeStart] and/or [onChangeEnd].
99
///
100
/// By default, a slider will be as wide as possible, centered vertically. When
101
/// given unbounded constraints, it will attempt to make the track 144 pixels
102
/// wide (with margins on each side) and will shrink-wrap vertically.
103
///
104 105
/// Requires one of its ancestors to be a [Material] widget.
///
106 107 108 109
/// Requires one of its ancestors to be a [MediaQuery] widget. Typically, these
/// are introduced by the [MaterialApp] or [WidgetsApp] widget at the top of
/// your application widget tree.
///
110 111 112 113 114 115 116
/// To determine how it should be displayed (e.g. colors, thumb shape, etc.),
/// a slider uses the [SliderThemeData] available from either a [SliderTheme]
/// widget or the [ThemeData.sliderTheme] a [Theme] widget above it in the
/// widget tree. You can also override some of the colors with the [activeColor]
/// and [inactiveColor] properties, although more fine-grained control of the
/// look is achieved using a [SliderThemeData].
///
117
/// See also:
118
///
119 120
///  * [SliderTheme] and [SliderThemeData] for information about controlling
///    the visual appearance of the slider.
121 122
///  * [Radio], for selecting among a set of explicit values.
///  * [Checkbox] and [Switch], for toggling a particular value on or off.
123
///  * <https://material.io/design/components/sliders.html>
124
///  * [MediaQuery], from which the text scale factor is obtained.
125
class Slider extends StatefulWidget {
126
  /// Creates a Material Design slider.
127 128
  ///
  /// The slider itself does not maintain any state. Instead, when the state of
129 130 131 132
  /// the slider changes, the widget calls the [onChanged] callback. Most
  /// widgets that use a slider will listen for the [onChanged] callback and
  /// rebuild the slider with a new [value] to update the visual appearance of
  /// the slider.
133 134
  ///
  /// * [value] determines currently selected value for this slider.
135 136 137 138 139 140
  /// * [onChanged] is called while the user is selecting a new value for the
  ///   slider.
  /// * [onChangeStart] is called when the user starts to select a new value for
  ///   the slider.
  /// * [onChangeEnd] is called when the user is done selecting a new value for
  ///   the slider.
141 142 143 144
  ///
  /// You can override some of the colors with the [activeColor] and
  /// [inactiveColor] properties, although more fine-grained control of the
  /// appearance is achieved using a [SliderThemeData].
145
  const Slider({
Hixie's avatar
Hixie committed
146
    Key key,
147 148
    @required this.value,
    @required this.onChanged,
149 150
    this.onChangeStart,
    this.onChangeEnd,
151 152
    this.min = 0.0,
    this.max = 1.0,
153 154
    this.divisions,
    this.label,
155
    this.activeColor,
156
    this.inactiveColor,
157
    this.mouseCursor,
158
    this.semanticFormatterCallback,
159 160
    this.focusNode,
    this.autofocus = false,
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
  }) : _sliderType = _SliderType.material,
       assert(value != null),
       assert(min != null),
       assert(max != null),
       assert(min <= max),
       assert(value >= min && value <= max),
       assert(divisions == null || divisions > 0),
       super(key: key);

  /// Creates a [CupertinoSlider] if the target platform is iOS, creates a
  /// Material Design slider otherwise.
  ///
  /// If a [CupertinoSlider] is created, the following parameters are
  /// ignored: [label], [inactiveColor], [semanticFormatterCallback].
  ///
  /// The target platform is based on the current [Theme]: [ThemeData.platform].
  const Slider.adaptive({
    Key key,
    @required this.value,
    @required this.onChanged,
    this.onChangeStart,
    this.onChangeEnd,
    this.min = 0.0,
    this.max = 1.0,
    this.divisions,
    this.label,
187
    this.mouseCursor,
188 189 190
    this.activeColor,
    this.inactiveColor,
    this.semanticFormatterCallback,
191 192
    this.focusNode,
    this.autofocus = false,
193 194
  }) : _sliderType = _SliderType.adaptive,
       assert(value != null),
195 196
       assert(min != null),
       assert(max != null),
197
       assert(min <= max),
198 199 200
       assert(value >= min && value <= max),
       assert(divisions == null || divisions > 0),
       super(key: key);
201

202 203 204
  /// The currently selected value for this slider.
  ///
  /// The slider's thumb is drawn at a position that corresponds to this value.
205
  final double value;
206

207 208
  /// Called during a drag when the user is selecting a new value for the slider
  /// by dragging.
209 210 211 212 213 214
  ///
  /// The slider passes the new value to the callback but does not actually
  /// change state until the parent widget rebuilds the slider with the new
  /// value.
  ///
  /// If null, the slider will be displayed as disabled.
215 216 217 218 219
  ///
  /// The callback provided to onChanged should update the state of the parent
  /// [StatefulWidget] using the [State.setState] method, so that the parent
  /// gets rebuilt; for example:
  ///
220
  /// {@tool snippet}
221
  ///
222
  /// ```dart
223
  /// Slider(
224 225 226 227 228 229 230 231 232 233
  ///   value: _duelCommandment.toDouble(),
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   label: '$_duelCommandment',
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _duelCommandment = newValue.round();
  ///     });
  ///   },
234
  /// )
235
  /// ```
236
  /// {@end-tool}
237 238 239 240 241 242 243
  ///
  /// See also:
  ///
  ///  * [onChangeStart] for a callback that is called when the user starts
  ///    changing the value.
  ///  * [onChangeEnd] for a callback that is called when the user stops
  ///    changing the value.
244 245
  final ValueChanged<double> onChanged;

246 247 248 249 250 251 252 253 254
  /// Called when the user starts selecting a new value for the slider.
  ///
  /// This callback shouldn't be used to update the slider [value] (use
  /// [onChanged] for that), but rather to be notified when the user has started
  /// selecting a new value by starting a drag or with a tap.
  ///
  /// The value passed will be the last [value] that the slider had before the
  /// change began.
  ///
255
  /// {@tool snippet}
256 257
  ///
  /// ```dart
258
  /// Slider(
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
  ///   value: _duelCommandment.toDouble(),
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   label: '$_duelCommandment',
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _duelCommandment = newValue.round();
  ///     });
  ///   },
  ///   onChangeStart: (double startValue) {
  ///     print('Started change at $startValue');
  ///   },
  /// )
  /// ```
274
  /// {@end-tool}
275 276 277 278 279 280 281 282 283 284 285 286 287
  ///
  /// See also:
  ///
  ///  * [onChangeEnd] for a callback that is called when the value change is
  ///    complete.
  final ValueChanged<double> onChangeStart;

  /// Called when the user is done selecting a new value for the slider.
  ///
  /// This callback shouldn't be used to update the slider [value] (use
  /// [onChanged] for that), but rather to know when the user has completed
  /// selecting a new [value] by ending a drag or a click.
  ///
288
  /// {@tool snippet}
289 290
  ///
  /// ```dart
291
  /// Slider(
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  ///   value: _duelCommandment.toDouble(),
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   label: '$_duelCommandment',
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _duelCommandment = newValue.round();
  ///     });
  ///   },
  ///   onChangeEnd: (double newValue) {
  ///     print('Ended change on $newValue');
  ///   },
  /// )
  /// ```
307
  /// {@end-tool}
308 309 310 311 312 313 314
  ///
  /// See also:
  ///
  ///  * [onChangeStart] for a callback that is called when a value change
  ///    begins.
  final ValueChanged<double> onChangeEnd;

315
  /// The minimum value the user can select.
316
  ///
317 318 319
  /// Defaults to 0.0. Must be less than or equal to [max].
  ///
  /// If the [max] is equal to the [min], then the slider is disabled.
Hixie's avatar
Hixie committed
320
  final double min;
321 322 323

  /// The maximum value the user can select.
  ///
324 325 326
  /// Defaults to 1.0. Must be greater than or equal to [min].
  ///
  /// If the [max] is equal to the [min], then the slider is disabled.
Hixie's avatar
Hixie committed
327
  final double max;
328

329 330 331 332 333 334 335 336 337
  /// The number of discrete divisions.
  ///
  /// Typically used with [label] to show the current discrete value.
  ///
  /// If null, the slider is continuous.
  final int divisions;

  /// A label to show above the slider when the slider is active.
  ///
338 339 340
  /// It is used to display the value of a discrete slider, and it is displayed
  /// as part of the value indicator shape.
  ///
341 342 343 344
  /// The label is rendered using the active [ThemeData]'s [TextTheme.bodyText1]
  /// text style, with the theme data's [ColorScheme.onPrimary] color. The
  /// label's text style can be overridden with
  /// [SliderThemeData.valueIndicatorTextStyle].
345 346 347
  ///
  /// If null, then the value indicator will not be displayed.
  ///
348 349
  /// Ignored if this slider is created with [Slider.adaptive].
  ///
350 351 352 353
  /// See also:
  ///
  ///  * [SliderComponentShape] for how to create a custom value indicator
  ///    shape.
354 355
  final String label;

356
  /// The color to use for the portion of the slider track that is active.
357
  ///
358 359
  /// The "active" side of the slider is the side between the thumb and the
  /// minimum value.
360
  ///
361 362
  /// Defaults to [SliderThemeData.activeTrackColor] of the current
  /// [SliderTheme].
363 364 365 366
  ///
  /// Using a [SliderTheme] gives much more fine-grained control over the
  /// appearance of various components of the slider.
  final Color activeColor;
367

368
  /// The color for the inactive portion of the slider track.
369
  ///
370 371
  /// The "inactive" side of the slider is the side between the thumb and the
  /// maximum value.
372
  ///
373
  /// Defaults to the [SliderThemeData.inactiveTrackColor] of the current
374
  /// [SliderTheme].
375
  ///
376 377
  /// Using a [SliderTheme] gives much more fine-grained control over the
  /// appearance of various components of the slider.
378 379
  ///
  /// Ignored if this slider is created with [Slider.adaptive].
380
  final Color inactiveColor;
381

382 383 384 385 386 387 388 389 390 391 392 393 394
  /// The cursor for a mouse pointer when it enters or is hovering over the
  /// widget.
  ///
  /// If [mouseCursor] is a [MaterialStateProperty<MouseCursor>],
  /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s:
  ///
  ///  * [MaterialState.hovered].
  ///  * [MaterialState.focused].
  ///  * [MaterialState.disabled].
  ///
  /// If this property is null, [MaterialStateMouseCursor.clickable] will be used.
  final MouseCursor mouseCursor;

395 396 397 398 399 400 401
  /// The callback used to create a semantic value from a slider value.
  ///
  /// Defaults to formatting values as a percentage.
  ///
  /// This is used by accessibility frameworks like TalkBack on Android to
  /// inform users what the currently selected value is with more context.
  ///
402
  /// {@tool snippet}
403 404 405 406 407
  ///
  /// In the example below, a slider for currency values is configured to
  /// announce a value with a currency label.
  ///
  /// ```dart
408
  /// Slider(
409 410 411 412 413 414 415 416 417 418 419 420 421 422
  ///   value: _dollars.toDouble(),
  ///   min: 20.0,
  ///   max: 330.0,
  ///   label: '$_dollars dollars',
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _dollars = newValue.round();
  ///     });
  ///   },
  ///   semanticFormatterCallback: (double newValue) {
  ///     return '${newValue.round()} dollars';
  ///   }
  ///  )
  /// ```
423
  /// {@end-tool}
424 425
  ///
  /// Ignored if this slider is created with [Slider.adaptive]
426 427
  final SemanticFormatterCallback semanticFormatterCallback;

428 429 430 431 432 433
  /// {@macro flutter.widgets.Focus.focusNode}
  final FocusNode focusNode;

  /// {@macro flutter.widgets.Focus.autofocus}
  final bool autofocus;

434 435
  final _SliderType _sliderType ;

436
  @override
437
  _SliderState createState() => _SliderState();
438 439

  @override
440 441
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
442
    properties.add(DoubleProperty('value', value));
443 444 445
    properties.add(ObjectFlagProperty<ValueChanged<double>>('onChanged', onChanged, ifNull: 'disabled'));
    properties.add(ObjectFlagProperty<ValueChanged<double>>.has('onChangeStart', onChangeStart));
    properties.add(ObjectFlagProperty<ValueChanged<double>>.has('onChangeEnd', onChangeEnd));
446 447
    properties.add(DoubleProperty('min', min));
    properties.add(DoubleProperty('max', max));
448 449 450 451 452
    properties.add(IntProperty('divisions', divisions));
    properties.add(StringProperty('label', label));
    properties.add(ColorProperty('activeColor', activeColor));
    properties.add(ColorProperty('inactiveColor', inactiveColor));
    properties.add(ObjectFlagProperty<ValueChanged<double>>.has('semanticFormatterCallback', semanticFormatterCallback));
453 454
    properties.add(ObjectFlagProperty<FocusNode>.has('focusNode', focusNode));
    properties.add(FlagProperty('autofocus', value: autofocus, ifTrue: 'autofocus'));
455
  }
456 457 458
}

class _SliderState extends State<Slider> with TickerProviderStateMixin {
459 460
  static const Duration enableAnimationDuration = Duration(milliseconds: 75);
  static const Duration valueIndicatorAnimationDuration = Duration(milliseconds: 100);
461 462 463 464 465 466 467

  // Animation controller that is run when the overlay (a.k.a radial reaction)
  // is shown in response to user interaction.
  AnimationController overlayController;
  // Animation controller that is run when the value indicator is being shown
  // or hidden.
  AnimationController valueIndicatorController;
468
  // Animation controller that is run when enabling/disabling the slider.
469
  AnimationController enableController;
470 471
  // Animation controller that is run when transitioning between one value
  // and the next on a discrete slider.
472
  AnimationController positionController;
473
  Timer interactionTimer;
474 475 476 477 478 479 480 481

  final GlobalKey _renderObjectKey = GlobalKey();
  // Keyboard mapping for a focused slider.
  Map<LogicalKeySet, Intent> _shortcutMap;
  // Action mapping for a focused slider.
  Map<Type, Action<Intent>> _actionMap;

  bool get _enabled => widget.onChanged != null;
482 483
  // Value Indicator Animation that appears on the Overlay.
  PaintValueIndicator paintValueIndicator;
484 485 486 487

  @override
  void initState() {
    super.initState();
488
    overlayController = AnimationController(
489 490 491
      duration: kRadialReactionDuration,
      vsync: this,
    );
492
    valueIndicatorController = AnimationController(
493 494 495
      duration: valueIndicatorAnimationDuration,
      vsync: this,
    );
496
    enableController = AnimationController(
497 498 499
      duration: enableAnimationDuration,
      vsync: this,
    );
500
    positionController = AnimationController(
501
      duration: Duration.zero,
502 503
      vsync: this,
    );
504
    enableController.value = widget.onChanged != null ? 1.0 : 0.0;
505
    positionController.value = _unlerp(widget.value);
506 507 508 509 510 511 512 513 514 515 516
    _shortcutMap = <LogicalKeySet, Intent>{
      LogicalKeySet(LogicalKeyboardKey.arrowUp): const _AdjustSliderIntent.up(),
      LogicalKeySet(LogicalKeyboardKey.arrowDown): const _AdjustSliderIntent.down(),
      LogicalKeySet(LogicalKeyboardKey.arrowLeft): const _AdjustSliderIntent.left(),
      LogicalKeySet(LogicalKeyboardKey.arrowRight): const _AdjustSliderIntent.right(),
    };
    _actionMap = <Type, Action<Intent>>{
      _AdjustSliderIntent: CallbackAction<_AdjustSliderIntent>(
        onInvoke: _actionHandler,
      ),
    };
517 518 519 520
  }

  @override
  void dispose() {
521
    interactionTimer?.cancel();
522 523
    overlayController.dispose();
    valueIndicatorController.dispose();
524 525
    enableController.dispose();
    positionController.dispose();
526 527 528 529
    if (overlayEntry != null) {
      overlayEntry.remove();
      overlayEntry = null;
    }
530
    super.dispose();
531 532
  }

Hixie's avatar
Hixie committed
533
  void _handleChanged(double value) {
534
    assert(widget.onChanged != null);
535 536 537 538
    final double lerpValue = _lerp(value);
    if (lerpValue != widget.value) {
      widget.onChanged(lerpValue);
    }
Hixie's avatar
Hixie committed
539 540
  }

541 542 543 544 545 546 547 548 549 550
  void _handleDragStart(double value) {
    assert(widget.onChangeStart != null);
    widget.onChangeStart(_lerp(value));
  }

  void _handleDragEnd(double value) {
    assert(widget.onChangeEnd != null);
    widget.onChangeEnd(_lerp(value));
  }

551
  void _actionHandler(_AdjustSliderIntent intent) {
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
    final _RenderSlider renderSlider = _renderObjectKey.currentContext.findRenderObject() as _RenderSlider;
    final TextDirection textDirection = Directionality.of(_renderObjectKey.currentContext);
    switch (intent.type) {
      case _SliderAdjustmentType.right:
        switch (textDirection) {
          case TextDirection.rtl:
            renderSlider.decreaseAction();
            break;
          case TextDirection.ltr:
            renderSlider.increaseAction();
            break;
        }
        break;
      case _SliderAdjustmentType.left:
        switch (textDirection) {
          case TextDirection.rtl:
            renderSlider.increaseAction();
            break;
          case TextDirection.ltr:
            renderSlider.decreaseAction();
            break;
        }
        break;
      case _SliderAdjustmentType.up:
        renderSlider.increaseAction();
        break;
      case _SliderAdjustmentType.down:
        renderSlider.decreaseAction();
        break;
    }
  }

  bool _focused = false;
  void _handleFocusHighlightChanged(bool focused) {
    if (focused != _focused) {
      setState(() { _focused = focused; });
    }
  }

  bool _hovering = false;
  void _handleHoverChanged(bool hovering) {
    if (hovering != _hovering) {
      setState(() { _hovering = hovering; });
    }
  }

598 599 600 601 602 603
  // Returns a number between min and max, proportional to value, which must
  // be between 0.0 and 1.0.
  double _lerp(double value) {
    assert(value >= 0.0);
    assert(value <= 1.0);
    return value * (widget.max - widget.min) + widget.min;
604 605
  }

606 607 608 609
  // Returns a number between 0.0 and 1.0, given a value between min and max.
  double _unlerp(double value) {
    assert(value <= widget.max);
    assert(value >= widget.min);
610
    return widget.max > widget.min ? (value - widget.min) / (widget.max - widget.min) : 0.0;
611
  }
612

613
  @override
614
  Widget build(BuildContext context) {
615
    assert(debugCheckHasMaterial(context));
616
    assert(debugCheckHasMediaQuery(context));
617

618 619 620 621 622 623 624 625 626 627
    switch (widget._sliderType) {
      case _SliderType.material:
        return _buildMaterialSlider(context);

      case _SliderType.adaptive: {
        final ThemeData theme = Theme.of(context);
        assert(theme.platform != null);
        switch (theme.platform) {
          case TargetPlatform.android:
          case TargetPlatform.fuchsia:
628 629
          case TargetPlatform.linux:
          case TargetPlatform.windows:
630 631
            return _buildMaterialSlider(context);
          case TargetPlatform.iOS:
632
          case TargetPlatform.macOS:
633 634 635 636 637 638 639 640 641
            return _buildCupertinoSlider(context);
        }
      }
    }
    assert(false);
    return null;
  }

  Widget _buildMaterialSlider(BuildContext context) {
642
    final ThemeData theme = Theme.of(context);
643 644 645 646
    SliderThemeData sliderTheme = SliderTheme.of(context);

    // If the widget has active or inactive colors specified, then we plug them
    // in to the slider theme as best we can. If the developer wants more
647 648 649 650
    // control than that, then they need to use a SliderTheme. The default
    // colors come from the ThemeData.colorScheme. These colors, along with
    // the default shapes and text styles are aligned to the Material
    // Guidelines.
651

652 653 654
    const double _defaultTrackHeight = 4;
    const SliderTrackShape _defaultTrackShape = RoundedRectSliderTrackShape();
    const SliderTickMarkShape _defaultTickMarkShape = RoundSliderTickMarkShape();
655
    const SliderComponentShape _defaultOverlayShape = RoundSliderOverlayShape();
656 657
    const SliderComponentShape _defaultThumbShape = RoundSliderThumbShape();
    const SliderComponentShape _defaultValueIndicatorShape = RectangularSliderValueIndicatorShape();
658 659 660 661 662 663 664 665 666 667 668 669 670 671
    const ShowValueIndicator _defaultShowValueIndicator = ShowValueIndicator.onlyForDiscrete;

    // The value indicator's color is not the same as the thumb and active track
    // (which can be defined by activeColor) if the
    // RectangularSliderValueIndicatorShape is used. In all other cases, the
    // value indicator is assumed to be the same as the active color.
    final SliderComponentShape valueIndicatorShape = sliderTheme.valueIndicatorShape ?? _defaultValueIndicatorShape;
    Color valueIndicatorColor;
    if (valueIndicatorShape is RectangularSliderValueIndicatorShape) {
      valueIndicatorColor = sliderTheme.valueIndicatorColor ?? Color.alphaBlend(theme.colorScheme.onSurface.withOpacity(0.60), theme.colorScheme.surface.withOpacity(0.90));
    } else {
      valueIndicatorColor = widget.activeColor ?? sliderTheme.valueIndicatorColor ?? theme.colorScheme.primary;
    }

672 673 674 675 676 677 678 679 680 681 682
    sliderTheme = sliderTheme.copyWith(
      trackHeight: sliderTheme.trackHeight ?? _defaultTrackHeight,
      activeTrackColor: widget.activeColor ?? sliderTheme.activeTrackColor ?? theme.colorScheme.primary,
      inactiveTrackColor: widget.inactiveColor ?? sliderTheme.inactiveTrackColor ?? theme.colorScheme.primary.withOpacity(0.24),
      disabledActiveTrackColor: sliderTheme.disabledActiveTrackColor ?? theme.colorScheme.onSurface.withOpacity(0.32),
      disabledInactiveTrackColor: sliderTheme.disabledInactiveTrackColor ?? theme.colorScheme.onSurface.withOpacity(0.12),
      activeTickMarkColor: widget.inactiveColor ?? sliderTheme.activeTickMarkColor ?? theme.colorScheme.onPrimary.withOpacity(0.54),
      inactiveTickMarkColor: widget.activeColor ?? sliderTheme.inactiveTickMarkColor ?? theme.colorScheme.primary.withOpacity(0.54),
      disabledActiveTickMarkColor: sliderTheme.disabledActiveTickMarkColor ?? theme.colorScheme.onPrimary.withOpacity(0.12),
      disabledInactiveTickMarkColor: sliderTheme.disabledInactiveTickMarkColor ?? theme.colorScheme.onSurface.withOpacity(0.12),
      thumbColor: widget.activeColor ?? sliderTheme.thumbColor ?? theme.colorScheme.primary,
683
      disabledThumbColor: sliderTheme.disabledThumbColor ?? Color.alphaBlend(theme.colorScheme.onSurface.withOpacity(.38), theme.colorScheme.surface),
684
      overlayColor: widget.activeColor?.withOpacity(0.12) ?? sliderTheme.overlayColor ?? theme.colorScheme.primary.withOpacity(0.12),
685
      valueIndicatorColor: valueIndicatorColor,
686 687 688 689
      trackShape: sliderTheme.trackShape ?? _defaultTrackShape,
      tickMarkShape: sliderTheme.tickMarkShape ?? _defaultTickMarkShape,
      thumbShape: sliderTheme.thumbShape ?? _defaultThumbShape,
      overlayShape: sliderTheme.overlayShape ?? _defaultOverlayShape,
690
      valueIndicatorShape: valueIndicatorShape,
691
      showValueIndicator: sliderTheme.showValueIndicator ?? _defaultShowValueIndicator,
692
      valueIndicatorTextStyle: sliderTheme.valueIndicatorTextStyle ?? theme.textTheme.bodyText1.copyWith(
693 694 695
        color: theme.colorScheme.onPrimary,
      ),
    );
696 697 698 699 700 701 702 703
    final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs<MouseCursor>(
      widget.mouseCursor ?? MaterialStateMouseCursor.clickable,
      <MaterialState>{
        if (!_enabled) MaterialState.disabled,
        if (_hovering) MaterialState.hovered,
        if (_focused) MaterialState.focused,
      },
    );
704

705 706 707 708 709
    // This size is used as the max bounds for the painting of the value
    // indicators It must be kept in sync with the function with the same name
    // in range_slider.dart.
    Size _screenSize() => MediaQuery.of(context).size;

710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
    return Semantics(
      container: true,
      child: FocusableActionDetector(
        actions: _actionMap,
        shortcuts: _shortcutMap,
        focusNode: widget.focusNode,
        autofocus: widget.autofocus,
        enabled: _enabled,
        onShowFocusHighlight: _handleFocusHighlightChanged,
        onShowHoverHighlight: _handleHoverChanged,
        mouseCursor: effectiveMouseCursor,
        child: CompositedTransformTarget(
          link: _layerLink,
          child: _SliderRenderObjectWidget(
            key: _renderObjectKey,
            value: _unlerp(widget.value),
            divisions: widget.divisions,
            label: widget.label,
            sliderTheme: sliderTheme,
            textScaleFactor: MediaQuery.of(context).textScaleFactor,
            screenSize: _screenSize(),
            onChanged: (widget.onChanged != null) && (widget.max > widget.min) ? _handleChanged : null,
            onChangeStart: widget.onChangeStart != null ? _handleDragStart : null,
            onChangeEnd: widget.onChangeEnd != null ? _handleDragEnd : null,
            state: this,
            semanticFormatterCallback: widget.semanticFormatterCallback,
            hasFocus: _focused,
            hovering: _hovering,
          ),
739
        ),
740
      ),
741 742
    );
  }
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761

  Widget _buildCupertinoSlider(BuildContext context) {
    // The render box of a slider has a fixed height but takes up the available
    // width. Wrapping the [CupertinoSlider] in this manner will help maintain
    // the same size.
    return SizedBox(
      width: double.infinity,
      child: CupertinoSlider(
        value: widget.value,
        onChanged: widget.onChanged,
        onChangeStart: widget.onChangeStart,
        onChangeEnd: widget.onChangeEnd,
        min: widget.min,
        max: widget.max,
        divisions: widget.divisions,
        activeColor: widget.activeColor,
      ),
    );
  }
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
  final LayerLink _layerLink = LayerLink();

  OverlayEntry overlayEntry;

  void showValueIndicator() {
    if (overlayEntry == null) {
      overlayEntry = OverlayEntry(
        builder: (BuildContext context) {
          return CompositedTransformFollower(
            link: _layerLink,
            child: _ValueIndicatorRenderObjectWidget(
              state: this,
            ),
          );
        },
      );
      Overlay.of(context).insert(overlayEntry);
    }
  }
781 782
}

783

784
class _SliderRenderObjectWidget extends LeafRenderObjectWidget {
785
  const _SliderRenderObjectWidget({
786 787 788 789
    Key key,
    this.value,
    this.divisions,
    this.label,
790
    this.sliderTheme,
791 792
    this.textScaleFactor,
    this.screenSize,
793
    this.onChanged,
794 795
    this.onChangeStart,
    this.onChangeEnd,
796
    this.state,
797
    this.semanticFormatterCallback,
798 799
    this.hasFocus,
    this.hovering,
800
  }) : super(key: key);
801 802

  final double value;
803 804
  final int divisions;
  final String label;
805
  final SliderThemeData sliderTheme;
806 807
  final double textScaleFactor;
  final Size screenSize;
808
  final ValueChanged<double> onChanged;
809 810
  final ValueChanged<double> onChangeStart;
  final ValueChanged<double> onChangeEnd;
811
  final SemanticFormatterCallback semanticFormatterCallback;
812
  final _SliderState state;
813 814
  final bool hasFocus;
  final bool hovering;
815

816
  @override
817
  _RenderSlider createRenderObject(BuildContext context) {
818
    return _RenderSlider(
819 820 821
      value: value,
      divisions: divisions,
      label: label,
822
      sliderTheme: sliderTheme,
823 824
      textScaleFactor: textScaleFactor,
      screenSize: screenSize,
825
      onChanged: onChanged,
826 827
      onChangeStart: onChangeStart,
      onChangeEnd: onChangeEnd,
828
      state: state,
829
      textDirection: Directionality.of(context),
830 831
      semanticFormatterCallback: semanticFormatterCallback,
      platform: Theme.of(context).platform,
832 833
      hasFocus: hasFocus,
      hovering: hovering,
834 835
    );
  }
836

837
  @override
838
  void updateRenderObject(BuildContext context, _RenderSlider renderObject) {
839 840
    renderObject
      ..value = value
841 842
      ..divisions = divisions
      ..label = label
843 844
      ..sliderTheme = sliderTheme
      ..theme = Theme.of(context)
845 846
      ..textScaleFactor = textScaleFactor
      ..screenSize = screenSize
847
      ..onChanged = onChanged
848 849
      ..onChangeStart = onChangeStart
      ..onChangeEnd = onChangeEnd
850 851
      ..textDirection = Directionality.of(context)
      ..semanticFormatterCallback = semanticFormatterCallback
852 853 854
      ..platform = Theme.of(context).platform
      ..hasFocus = hasFocus
      ..hovering = hovering;
855 856
    // Ticker provider cannot change since there's a 1:1 relationship between
    // the _SliderRenderObjectWidget object and the _SliderState object.
857 858 859
  }
}

860
class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
861
  _RenderSlider({
862
    @required double value,
863 864
    int divisions,
    String label,
865
    SliderThemeData sliderTheme,
866 867
    double textScaleFactor,
    Size screenSize,
868
    TargetPlatform platform,
869
    ValueChanged<double> onChanged,
870
    SemanticFormatterCallback semanticFormatterCallback,
871 872
    this.onChangeStart,
    this.onChangeEnd,
873
    @required _SliderState state,
874
    @required TextDirection textDirection,
875 876
    bool hasFocus,
    bool hovering,
877
  }) : assert(value != null && value >= 0.0 && value <= 1.0),
878 879 880 881 882 883 884 885 886 887 888 889 890
        assert(state != null),
        assert(textDirection != null),
        _platform = platform,
        _semanticFormatterCallback = semanticFormatterCallback,
        _label = label,
        _value = value,
        _divisions = divisions,
        _sliderTheme = sliderTheme,
        _textScaleFactor = textScaleFactor,
        _screenSize = screenSize,
        _onChanged = onChanged,
        _state = state,
        _textDirection = textDirection,
891
        _hasFocus = hasFocus,
892
        _hovering = hovering {
Ian Hickson's avatar
Ian Hickson committed
893
    _updateLabelPainter();
894 895
    final GestureArenaTeam team = GestureArenaTeam();
    _drag = HorizontalDragGestureRecognizer()
896
      ..team = team
897 898
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
899 900
      ..onEnd = _handleDragEnd
      ..onCancel = _endInteraction;
901
    _tap = TapGestureRecognizer()
902
      ..team = team
903
      ..onTapDown = _handleTapDown
904 905
      ..onTapUp = _handleTapUp
      ..onTapCancel = _endInteraction;
906
    _overlayAnimation = CurvedAnimation(
907 908 909
      parent: _state.overlayController,
      curve: Curves.fastOutSlowIn,
    );
910
    _valueIndicatorAnimation = CurvedAnimation(
911
      parent: _state.valueIndicatorController,
912
      curve: Curves.fastOutSlowIn,
913 914 915 916 917 918
    )..addStatusListener((AnimationStatus status) {
      if (status == AnimationStatus.dismissed && _state.overlayEntry != null) {
        _state.overlayEntry.remove();
        _state.overlayEntry = null;
      }
    });
919
    _enableAnimation = CurvedAnimation(
920 921 922
      parent: _state.enableController,
      curve: Curves.easeInOut,
    );
923
  }
924 925
  static const Duration _positionAnimationDuration = Duration(milliseconds: 75);
  static const Duration _minimumInteractionTime = Duration(milliseconds: 500);
926 927 928 929 930 931 932 933

  // This value is the touch target, 48, multiplied by 3.
  static const double _minPreferredTrackWidth = 144.0;

  // Compute the largest width and height needed to paint the slider shapes,
  // other than the track shape. It is assumed that these shapes are vertically
  // centered on the track.
  double get _maxSliderPartWidth => _sliderPartSizes.map((Size size) => size.width).reduce(math.max);
934
  double get _maxSliderPartHeight => _sliderPartSizes.map((Size size) => size.height).reduce(math.max);
935 936 937 938 939
  List<Size> get _sliderPartSizes => <Size>[
    _sliderTheme.overlayShape.getPreferredSize(isInteractive, isDiscrete),
    _sliderTheme.thumbShape.getPreferredSize(isInteractive, isDiscrete),
    _sliderTheme.tickMarkShape.getPreferredSize(isEnabled: isInteractive, sliderTheme: sliderTheme),
  ];
940
  double get _minPreferredTrackHeight => _sliderTheme.trackHeight;
941

942
  final _SliderState _state;
943 944 945
  Animation<double> _overlayAnimation;
  Animation<double> _valueIndicatorAnimation;
  Animation<double> _enableAnimation;
946
  final TextPainter _labelPainter = TextPainter();
947 948 949 950 951
  HorizontalDragGestureRecognizer _drag;
  TapGestureRecognizer _tap;
  bool _active = false;
  double _currentDragValue = 0.0;

952 953 954 955 956 957 958 959 960
  // This rect is used in gesture calculations, where the gesture coordinates
  // are relative to the sliders origin. Therefore, the offset is passed as
  // (0,0).
  Rect get _trackRect => _sliderTheme.trackShape.getPreferredRect(
    parentBox: this,
    offset: Offset.zero,
    sliderTheme: _sliderTheme,
    isDiscrete: false,
  );
961 962 963 964

  bool get isInteractive => onChanged != null;

  bool get isDiscrete => divisions != null && divisions > 0;
965

966 967
  double get value => _value;
  double _value;
968
  set value(double newValue) {
969
    assert(newValue != null && newValue >= 0.0 && newValue <= 1.0);
970 971
    final double convertedValue = isDiscrete ? _discretize(newValue) : newValue;
    if (convertedValue == _value) {
972
      return;
973 974 975
    }
    _value = convertedValue;
    if (isDiscrete) {
976 977 978 979 980 981 982
      // Reset the duration to match the distance that we're traveling, so that
      // whatever the distance, we still do it in _positionAnimationDuration,
      // and if we get re-targeted in the middle, it still takes that long to
      // get to the new location.
      final double distance = (_value - _state.positionController.value).abs();
      _state.positionController.duration = distance != 0.0
        ? _positionAnimationDuration * (1.0 / distance)
983
        : Duration.zero;
984 985 986 987
      _state.positionController.animateTo(convertedValue, curve: Curves.easeInOut);
    } else {
      _state.positionController.value = convertedValue;
    }
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    markNeedsSemanticsUpdate();
  }

  TargetPlatform _platform;
  TargetPlatform get platform => _platform;
  set platform(TargetPlatform value) {
    if (_platform == value)
      return;
    _platform = value;
    markNeedsSemanticsUpdate();
  }

  SemanticFormatterCallback _semanticFormatterCallback;
  SemanticFormatterCallback get semanticFormatterCallback => _semanticFormatterCallback;
  set semanticFormatterCallback(SemanticFormatterCallback value) {
    if (_semanticFormatterCallback == value)
      return;
    _semanticFormatterCallback = value;
    markNeedsSemanticsUpdate();
1007 1008 1009 1010
  }

  int get divisions => _divisions;
  int _divisions;
1011
  set divisions(int value) {
1012
    if (value == _divisions) {
1013
      return;
1014
    }
1015
    _divisions = value;
1016 1017 1018 1019 1020
    markNeedsPaint();
  }

  String get label => _label;
  String _label;
1021
  set label(String value) {
1022
    if (value == _label) {
1023
      return;
1024
    }
1025
    _label = value;
Ian Hickson's avatar
Ian Hickson committed
1026
    _updateLabelPainter();
1027 1028
  }

1029 1030 1031 1032
  SliderThemeData get sliderTheme => _sliderTheme;
  SliderThemeData _sliderTheme;
  set sliderTheme(SliderThemeData value) {
    if (value == _sliderTheme) {
1033
      return;
1034 1035
    }
    _sliderTheme = value;
1036 1037 1038
    markNeedsPaint();
  }

1039 1040 1041 1042
  ThemeData get theme => _theme;
  ThemeData _theme;
  set theme(ThemeData value) {
    if (value == _theme) {
1043
      return;
1044 1045
    }
    _theme = value;
1046 1047 1048
    markNeedsPaint();
  }

1049 1050 1051 1052
  double get textScaleFactor => _textScaleFactor;
  double _textScaleFactor;
  set textScaleFactor(double value) {
    if (value == _textScaleFactor) {
1053
      return;
1054
    }
1055
    _textScaleFactor = value;
1056 1057 1058
    _updateLabelPainter();
  }

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
  Size get screenSize => _screenSize;
  Size _screenSize;
  set screenSize(Size value) {
    if (value == _screenSize) {
      return;
    }
    _screenSize = value;
    markNeedsPaint();
  }

1069 1070 1071
  ValueChanged<double> get onChanged => _onChanged;
  ValueChanged<double> _onChanged;
  set onChanged(ValueChanged<double> value) {
1072
    if (value == _onChanged) {
1073
      return;
1074
    }
1075 1076 1077
    final bool wasInteractive = isInteractive;
    _onChanged = value;
    if (wasInteractive != isInteractive) {
1078 1079 1080 1081 1082
      if (isInteractive) {
        _state.enableController.forward();
      } else {
        _state.enableController.reverse();
      }
1083
      markNeedsPaint();
1084
      markNeedsSemanticsUpdate();
1085 1086
    }
  }
1087

1088 1089 1090
  ValueChanged<double> onChangeStart;
  ValueChanged<double> onChangeEnd;

1091 1092 1093 1094
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    assert(value != null);
1095
    if (value == _textDirection) {
1096
      return;
1097
    }
1098
    _textDirection = value;
Ian Hickson's avatar
Ian Hickson committed
1099 1100 1101
    _updateLabelPainter();
  }

1102 1103 1104 1105 1106 1107 1108 1109 1110
  /// True if this slider has the input focus.
  bool get hasFocus => _hasFocus;
  bool _hasFocus;
  set hasFocus(bool value) {
    assert(value != null);
    if (value == _hasFocus)
      return;
    _hasFocus = value;
    _updateForFocusOrHover(_hasFocus);
1111
    markNeedsSemanticsUpdate();
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
  }

  /// True if this slider is being hovered over by a pointer.
  bool get hovering => _hovering;
  bool _hovering;
  set hovering(bool value) {
    assert(value != null);
    if (value == _hovering)
      return;
    _hovering = value;
    _updateForFocusOrHover(_hovering);
  }

  void _updateForFocusOrHover(bool hasFocusOrIsHovering) {
    if (hasFocusOrIsHovering) {
      _state.overlayController.forward();
      if (showValueIndicator) {
        _state.valueIndicatorController.forward();
      }
    } else {
      _state.overlayController.reverse();
      if (showValueIndicator) {
        _state.valueIndicatorController.reverse();
      }
    }
  }
1138

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
  bool get showValueIndicator {
    bool showValueIndicator;
    switch (_sliderTheme.showValueIndicator) {
      case ShowValueIndicator.onlyForDiscrete:
        showValueIndicator = isDiscrete;
        break;
      case ShowValueIndicator.onlyForContinuous:
        showValueIndicator = !isDiscrete;
        break;
      case ShowValueIndicator.always:
        showValueIndicator = true;
        break;
      case ShowValueIndicator.never:
        showValueIndicator = false;
        break;
    }
    return showValueIndicator;
  }

1158 1159 1160
  double get _adjustmentUnit {
    switch (_platform) {
      case TargetPlatform.iOS:
1161
      case TargetPlatform.macOS:
1162
        // Matches iOS implementation of material slider.
1163 1164 1165
        return 0.1;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
1166 1167 1168
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        // Matches Android implementation of material slider.
1169 1170
        return 0.05;
    }
1171
    assert(false, 'Unhandled TargetPlatform $_platform');
1172
    return 0.0;
1173 1174
  }

Ian Hickson's avatar
Ian Hickson committed
1175 1176 1177
  void _updateLabelPainter() {
    if (label != null) {
      _labelPainter
1178
        ..text = TextSpan(
1179 1180 1181
          style: _sliderTheme.valueIndicatorTextStyle,
          text: label,
        )
Ian Hickson's avatar
Ian Hickson committed
1182
        ..textDirection = textDirection
1183
        ..textScaleFactor = textScaleFactor
Ian Hickson's avatar
Ian Hickson committed
1184 1185 1186 1187 1188 1189 1190 1191
        ..layout();
    } else {
      _labelPainter.text = null;
    }
    // Changing the textDirection can result in the layout changing, because the
    // bidi algorithm might line up the glyphs differently which can result in
    // different ligatures, different shapes, etc. So we always markNeedsLayout.
    markNeedsLayout();
1192 1193
  }

1194 1195 1196 1197 1198 1199 1200
  @override
  void systemFontsDidChange() {
    super.systemFontsDidChange();
    _labelPainter.markNeedsLayout();
    _updateLabelPainter();
  }

1201 1202 1203
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
1204 1205
    _overlayAnimation.addListener(markNeedsPaint);
    _valueIndicatorAnimation.addListener(markNeedsPaint);
1206 1207 1208 1209 1210 1211
    _enableAnimation.addListener(markNeedsPaint);
    _state.positionController.addListener(markNeedsPaint);
  }

  @override
  void detach() {
1212 1213
    _overlayAnimation.removeListener(markNeedsPaint);
    _valueIndicatorAnimation.removeListener(markNeedsPaint);
1214 1215 1216 1217 1218
    _enableAnimation.removeListener(markNeedsPaint);
    _state.positionController.removeListener(markNeedsPaint);
    super.detach();
  }

1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
  double _getValueFromVisualPosition(double visualPosition) {
    switch (textDirection) {
      case TextDirection.rtl:
        return 1.0 - visualPosition;
      case TextDirection.ltr:
        return visualPosition;
    }
    return null;
  }

1229
  double _getValueFromGlobalPosition(Offset globalPosition) {
1230
    final double visualPosition = (globalToLocal(globalPosition).dx - _trackRect.left) / _trackRect.width;
1231
    return _getValueFromVisualPosition(visualPosition);
1232 1233
  }

1234
  double _discretize(double value) {
1235
    double result = value.clamp(0.0, 1.0) as double;
1236
    if (isDiscrete) {
1237
      result = (result * divisions).round() / divisions;
1238
    }
1239 1240
    return result;
  }
1241

1242
  void _startInteraction(Offset globalPosition) {
1243
    _state.showValueIndicator();
1244
    if (isInteractive) {
1245
      _active = true;
1246 1247 1248 1249 1250 1251
      // We supply the *current* value as the start location, so that if we have
      // a tap, it consists of a call to onChangeStart with the previous value and
      // a call to onChangeEnd with the new value.
      if (onChangeStart != null) {
        onChangeStart(_discretize(value));
      }
1252
      _currentDragValue = _getValueFromGlobalPosition(globalPosition);
1253
      onChanged(_discretize(_currentDragValue));
1254 1255 1256
      _state.overlayController.forward();
      if (showValueIndicator) {
        _state.valueIndicatorController.forward();
1257
        _state.interactionTimer?.cancel();
1258
        _state.interactionTimer = Timer(_minimumInteractionTime * timeDilation, () {
1259 1260 1261
          _state.interactionTimer = null;
          if (!_active &&
              _state.valueIndicatorController.status == AnimationStatus.completed) {
1262 1263 1264 1265
            _state.valueIndicatorController.reverse();
          }
        });
      }
1266 1267 1268 1269
    }
  }

  void _endInteraction() {
1270 1271 1272 1273
    if (!_state.mounted) {
      return;
    }

1274
    if (_active && _state.mounted) {
1275 1276 1277
      if (onChangeEnd != null) {
        onChangeEnd(_discretize(_currentDragValue));
      }
1278 1279
      _active = false;
      _currentDragValue = 0.0;
1280
      _state.overlayController.reverse();
1281

1282
      if (showValueIndicator && _state.interactionTimer == null) {
1283 1284
        _state.valueIndicatorController.reverse();
      }
1285 1286 1287
    }
  }

1288 1289 1290
  void _handleDragStart(DragStartDetails details) {
    _startInteraction(details.globalPosition);
  }
1291

1292
  void _handleDragUpdate(DragUpdateDetails details) {
1293 1294 1295 1296
    if (!_state.mounted) {
      return;
    }

1297
    if (isInteractive) {
1298
      final double valueDelta = details.primaryDelta / _trackRect.width;
1299 1300 1301 1302 1303 1304 1305 1306
      switch (textDirection) {
        case TextDirection.rtl:
          _currentDragValue -= valueDelta;
          break;
        case TextDirection.ltr:
          _currentDragValue += valueDelta;
          break;
      }
1307
      onChanged(_discretize(_currentDragValue));
1308 1309 1310
    }
  }

1311 1312 1313
  void _handleDragEnd(DragEndDetails details) {
    _endInteraction();
  }
1314

1315 1316 1317
  void _handleTapDown(TapDownDetails details) {
    _startInteraction(details.globalPosition);
  }
1318

1319 1320 1321
  void _handleTapUp(TapUpDetails details) {
    _endInteraction();
  }
1322

1323
  @override
1324
  bool hitTestSelf(Offset position) => true;
1325

1326
  @override
Ian Hickson's avatar
Ian Hickson committed
1327
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
1328
    assert(debugHandleEvent(event, entry));
1329 1330
    if (event is PointerDownEvent && isInteractive) {
      // We need to add the drag first so that it has priority.
1331
      _drag.addPointer(event);
1332 1333
      _tap.addPointer(event);
    }
1334 1335
  }

1336
  @override
1337
  double computeMinIntrinsicWidth(double height) => _minPreferredTrackWidth + _maxSliderPartWidth;
1338 1339

  @override
1340
  double computeMaxIntrinsicWidth(double height) => _minPreferredTrackWidth + _maxSliderPartWidth;
1341 1342

  @override
1343
  double computeMinIntrinsicHeight(double width) => math.max(_minPreferredTrackHeight, _maxSliderPartHeight);
1344 1345

  @override
1346
  double computeMaxIntrinsicHeight(double width) => math.max(_minPreferredTrackHeight, _maxSliderPartHeight);
1347 1348 1349 1350 1351 1352

  @override
  bool get sizedByParent => true;

  @override
  void performResize() {
1353
    size = Size(
1354
      constraints.hasBoundedWidth ? constraints.maxWidth : _minPreferredTrackWidth + _maxSliderPartWidth,
1355
      constraints.hasBoundedHeight ? constraints.maxHeight : math.max(_minPreferredTrackHeight, _maxSliderPartHeight),
1356 1357 1358
    );
  }

1359
  @override
1360
  void paint(PaintingContext context, Offset offset) {
1361
    final double value = _state.positionController.value;
1362

1363 1364 1365
    // The visual position is the position of the thumb from 0 to 1 from left
    // to right. In left to right, this is the same as the value, but it is
    // reversed for right to left text.
1366 1367 1368 1369 1370 1371 1372 1373 1374
    double visualPosition;
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - value;
        break;
      case TextDirection.ltr:
        visualPosition = value;
        break;
    }
1375

1376 1377 1378 1379
    final Rect trackRect = _sliderTheme.trackShape.getPreferredRect(
      parentBox: this,
      offset: offset,
      sliderTheme: _sliderTheme,
1380
      isDiscrete: isDiscrete,
1381
    );
1382
    final Offset thumbCenter = Offset(trackRect.left + visualPosition * trackRect.width, trackRect.center.dy);
1383

1384 1385 1386 1387 1388 1389 1390 1391 1392
    _sliderTheme.trackShape.paint(
      context,
      offset,
      parentBox: this,
      sliderTheme: _sliderTheme,
      enableAnimation: _enableAnimation,
      textDirection: _textDirection,
      thumbCenter: thumbCenter,
      isDiscrete: isDiscrete,
1393
      isEnabled: isInteractive,
1394 1395
    );

1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
    if (!_overlayAnimation.isDismissed) {
      _sliderTheme.overlayShape.paint(
        context,
        thumbCenter,
        activationAnimation: _overlayAnimation,
        enableAnimation: _enableAnimation,
        isDiscrete: isDiscrete,
        labelPainter: _labelPainter,
        parentBox: this,
        sliderTheme: _sliderTheme,
        textDirection: _textDirection,
        value: _value,
      );
    }

    if (isDiscrete) {
      final double tickMarkWidth = _sliderTheme.tickMarkShape.getPreferredSize(
        isEnabled: isInteractive,
        sliderTheme: _sliderTheme,
      ).width;
1416
      final double padding = trackRect.height;
1417
      final double adjustedTrackWidth = trackRect.width - padding;
1418 1419 1420
      // If the tick marks would be too dense, don't bother painting them.
      if (adjustedTrackWidth / divisions >= 3.0 * tickMarkWidth) {
        final double dy = trackRect.center.dy;
1421
        for (int i = 0; i <= divisions; i++) {
1422
          final double value = i / divisions;
1423 1424
          // The ticks are mapped to be within the track, so the tick mark width
          // must be subtracted from the track width.
1425
          final double dx = trackRect.left + value * adjustedTrackWidth + padding / 2;
1426
          final Offset tickMarkOffset = Offset(dx, dy);
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
          _sliderTheme.tickMarkShape.paint(
            context,
            tickMarkOffset,
            parentBox: this,
            sliderTheme: _sliderTheme,
            enableAnimation: _enableAnimation,
            textDirection: _textDirection,
            thumbCenter: thumbCenter,
            isEnabled: isInteractive,
          );
        }
1438 1439 1440 1441
      }
    }

    if (isInteractive && label != null && !_valueIndicatorAnimation.isDismissed) {
1442
      if (showValueIndicator) {
1443
        _state.paintValueIndicator = (PaintingContext context, Offset offset) {
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
          if (attached) {
            _sliderTheme.valueIndicatorShape.paint(
              context,
              offset + thumbCenter,
              activationAnimation: _valueIndicatorAnimation,
              enableAnimation: _enableAnimation,
              isDiscrete: isDiscrete,
              labelPainter: _labelPainter,
              parentBox: this,
              sliderTheme: _sliderTheme,
              textDirection: _textDirection,
              value: _value,
              textScaleFactor: textScaleFactor,
              sizeWithOverflow: screenSize.isEmpty ? size : screenSize,
            );
          }
1460
        };
1461
      }
1462
    }
Adam Barth's avatar
Adam Barth committed
1463

1464 1465 1466
    _sliderTheme.thumbShape.paint(
      context,
      thumbCenter,
1467
      activationAnimation: _overlayAnimation,
1468 1469 1470 1471 1472 1473
      enableAnimation: _enableAnimation,
      isDiscrete: isDiscrete,
      labelPainter: _labelPainter,
      parentBox: this,
      sliderTheme: _sliderTheme,
      textDirection: _textDirection,
1474
      sizeWithOverflow: screenSize.isEmpty ? size : screenSize,
1475
      value: _value,
1476
    );
1477
  }
1478 1479

  @override
1480 1481
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
1482

1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
    // The Slider widget has its own Focus widget with semantics information,
    // and we want that semantics node to collect the semantics information here
    // so that it's all in the same node: otherwise Talkback sees that the node
    // has focusable children, and it won't focus the Slider's Focus widget
    // because it thinks the Focus widget's node doesn't have anything to say
    // (which it doesn't, but this child does). Aggregating the semantic
    // information into one node means that Talkback will recognize that it has
    // something to say and focus it when it receives keyboard focus.
    // (See https://github.com/flutter/flutter/issues/57038 for context).
    config.isSemanticBoundary = false;

    config.isEnabled = isInteractive;
    config.textDirection = textDirection;
1496
    if (isInteractive) {
1497 1498
      config.onIncrease = increaseAction;
      config.onDecrease = decreaseAction;
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
    }
    config.label = _label ?? '';
    if (semanticFormatterCallback != null) {
      config.value = semanticFormatterCallback(_state._lerp(value));
      config.increasedValue = semanticFormatterCallback(_state._lerp((value + _semanticActionUnit).clamp(0.0, 1.0) as double));
      config.decreasedValue = semanticFormatterCallback(_state._lerp((value - _semanticActionUnit).clamp(0.0, 1.0) as double));
    } else {
      config.value = '${(value * 100).round()}%';
      config.increasedValue = '${((value + _semanticActionUnit).clamp(0.0, 1.0) * 100).round()}%';
      config.decreasedValue = '${((value - _semanticActionUnit).clamp(0.0, 1.0) * 100).round()}%';
1509 1510 1511
    }
  }

1512
  double get _semanticActionUnit => divisions != null ? 1.0 / divisions : _adjustmentUnit;
1513

1514
  void increaseAction() {
1515
    if (isInteractive) {
1516
      onChanged((value + _semanticActionUnit).clamp(0.0, 1.0) as double);
1517
    }
1518 1519
  }

1520
  void decreaseAction() {
1521
    if (isInteractive) {
1522
      onChanged((value - _semanticActionUnit).clamp(0.0, 1.0) as double);
1523
    }
1524
  }
1525
}
1526

1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
class _AdjustSliderIntent extends Intent {
  const _AdjustSliderIntent({
    @required this.type
  });

  const _AdjustSliderIntent.right() : type = _SliderAdjustmentType.right;

  const _AdjustSliderIntent.left() : type = _SliderAdjustmentType.left;

  const _AdjustSliderIntent.up() : type = _SliderAdjustmentType.up;

  const _AdjustSliderIntent.down() : type = _SliderAdjustmentType.down;

  final _SliderAdjustmentType type;
}

enum _SliderAdjustmentType {
  right,
  left,
  up,
  down,
}

1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
class _ValueIndicatorRenderObjectWidget extends LeafRenderObjectWidget {
  const _ValueIndicatorRenderObjectWidget({
    this.state,
  });

  final _SliderState state;

  @override
  _RenderValueIndicator createRenderObject(BuildContext context) {
    return _RenderValueIndicator(
      state: state,
    );
  }
  @override
  void updateRenderObject(BuildContext context, _RenderValueIndicator renderObject) {
    renderObject._state = state;
  }
}

class _RenderValueIndicator extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
  _RenderValueIndicator({
    _SliderState state,
  }) : _state = state {
    _valueIndicatorAnimation = CurvedAnimation(
      parent: _state.valueIndicatorController,
      curve: Curves.fastOutSlowIn,
    );
  }
  Animation<double> _valueIndicatorAnimation;
  _SliderState _state;

  @override
  bool get sizedByParent => true;

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    _valueIndicatorAnimation.addListener(markNeedsPaint);
    _state.positionController.addListener(markNeedsPaint);
  }

  @override
  void detach() {
    _valueIndicatorAnimation.removeListener(markNeedsPaint);
    _state.positionController.removeListener(markNeedsPaint);
    super.detach();
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    if (_state.paintValueIndicator != null) {
      _state.paintValueIndicator(context, offset);
    }
  }
}