slider.dart 51.8 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 'dart:async';
6
import 'dart:math' as math;
7
import 'dart:math';
8

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

17
import 'constants.dart';
18
import 'debug.dart';
19 20
import 'material.dart';
import 'slider_theme.dart';
21 22
import 'theme.dart';

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

28 29 30 31
/// A callback that formats a numeric value from a [Slider] widget.
///
/// See also:
///
32
///  * [Slider.semanticFormatterCallback], which shows an example use case.
33
typedef SemanticFormatterCallback = String Function(double value);
34

35 36 37 38 39 40
/// [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);

41 42
enum _SliderType { material, adaptive }

43
/// A Material Design slider.
44
///
45 46 47
/// Used to select from a range of values.
///
/// A slider can be used to select from either a continuous or a discrete set of
48 49
/// 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
50
/// indicates the number of discrete intervals. For example, if [min] is 0.0 and
51
/// [max] is 50.0 and [divisions] is 5, then the slider can take on the
52
/// discrete values 0.0, 10.0, 20.0, 30.0, 40.0, and 50.0.
53
///
54 55 56 57
/// The terms for the parts of a slider are:
///
///  * The "thumb", which is a shape that slides horizontally when the user
///    drags it.
58
///  * The "track", which is the line that the slider thumb slides along.
59 60 61 62 63 64 65
///  * 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.
///
66 67 68
/// 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]).
///
69 70 71 72
/// 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
73 74
/// slider. To know when the value starts to change, or when it is done
/// changing, set the optional callbacks [onChangeStart] and/or [onChangeEnd].
75
///
76
/// By default, a slider will be as wide as possible, centered vertically. When
77
/// given unbounded constraints, it will attempt to make the track 144 pixels
78
/// wide (with margins on each side) and will shrink-wrap vertically.
79
///
80 81
/// Requires one of its ancestors to be a [Material] widget.
///
82 83 84 85
/// 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.
///
86 87 88 89 90 91 92
/// 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].
///
93
/// See also:
94
///
95 96
///  * [SliderTheme] and [SliderThemeData] for information about controlling
///    the visual appearance of the slider.
97 98
///  * [Radio], for selecting among a set of explicit values.
///  * [Checkbox] and [Switch], for toggling a particular value on or off.
99
///  * <https://material.io/design/components/sliders.html>
100
///  * [MediaQuery], from which the text scale factor is obtained.
101
class Slider extends StatefulWidget {
102
  /// Creates a Material Design slider.
103 104
  ///
  /// The slider itself does not maintain any state. Instead, when the state of
105 106 107 108
  /// 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.
109 110
  ///
  /// * [value] determines currently selected value for this slider.
111 112 113 114 115 116
  /// * [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.
117 118 119 120
  ///
  /// 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].
121
  const Slider({
Hixie's avatar
Hixie committed
122
    Key key,
123 124
    @required this.value,
    @required this.onChanged,
125 126
    this.onChangeStart,
    this.onChangeEnd,
127 128
    this.min = 0.0,
    this.max = 1.0,
129 130
    this.divisions,
    this.label,
131
    this.activeColor,
132
    this.inactiveColor,
133
    this.semanticFormatterCallback,
134 135
    this.focusNode,
    this.autofocus = false,
136
    this.useV2Slider = false,
137 138 139 140 141 142 143
  }) : _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),
144
       assert(useV2Slider != null),
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
       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,
    this.activeColor,
    this.inactiveColor,
    this.semanticFormatterCallback,
167 168
    this.focusNode,
    this.autofocus = false,
169
    this.useV2Slider = false,
170 171
  }) : _sliderType = _SliderType.adaptive,
       assert(value != null),
172 173
       assert(min != null),
       assert(max != null),
174
       assert(min <= max),
175 176
       assert(value >= min && value <= max),
       assert(divisions == null || divisions > 0),
177
       assert(useV2Slider != null),
178
       super(key: key);
179

180 181 182
  /// The currently selected value for this slider.
  ///
  /// The slider's thumb is drawn at a position that corresponds to this value.
183
  final double value;
184

185 186
  /// Called during a drag when the user is selecting a new value for the slider
  /// by dragging.
187 188 189 190 191 192
  ///
  /// 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.
193 194 195 196 197
  ///
  /// 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:
  ///
198
  /// {@tool snippet}
199
  ///
200
  /// ```dart
201
  /// Slider(
202 203 204 205 206 207 208 209 210 211
  ///   value: _duelCommandment.toDouble(),
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   label: '$_duelCommandment',
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _duelCommandment = newValue.round();
  ///     });
  ///   },
212
  /// )
213
  /// ```
214
  /// {@end-tool}
215 216 217 218 219 220 221
  ///
  /// 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.
222 223
  final ValueChanged<double> onChanged;

224 225 226 227 228 229 230 231 232
  /// 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.
  ///
233
  /// {@tool snippet}
234 235
  ///
  /// ```dart
236
  /// Slider(
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
  ///   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');
  ///   },
  /// )
  /// ```
252
  /// {@end-tool}
253 254 255 256 257 258 259 260 261 262 263 264 265
  ///
  /// 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.
  ///
266
  /// {@tool snippet}
267 268
  ///
  /// ```dart
269
  /// Slider(
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
  ///   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');
  ///   },
  /// )
  /// ```
285
  /// {@end-tool}
286 287 288 289 290 291 292
  ///
  /// See also:
  ///
  ///  * [onChangeStart] for a callback that is called when a value change
  ///    begins.
  final ValueChanged<double> onChangeEnd;

293
  /// The minimum value the user can select.
294
  ///
295 296 297
  /// 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
298
  final double min;
299 300 301

  /// The maximum value the user can select.
  ///
302 303 304
  /// 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
305
  final double max;
306

307 308 309 310 311 312 313 314 315
  /// 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.
  ///
316 317 318 319
  /// It is used to display the value of a discrete slider, and it is displayed
  /// as part of the value indicator shape.
  ///
  /// The label is rendered using the active [ThemeData]'s
320
  /// [ThemeData.textTheme.bodyText1] text style, with the
321 322
  /// theme data's [ThemeData.colorScheme.onPrimaryColor]. The label's text style
  /// can be overridden with [SliderThemeData.valueIndicatorTextStyle].
323 324 325
  ///
  /// If null, then the value indicator will not be displayed.
  ///
326 327
  /// Ignored if this slider is created with [Slider.adaptive].
  ///
328 329 330 331
  /// See also:
  ///
  ///  * [SliderComponentShape] for how to create a custom value indicator
  ///    shape.
332 333
  final String label;

334
  /// The color to use for the portion of the slider track that is active.
335
  ///
336 337
  /// The "active" side of the slider is the side between the thumb and the
  /// minimum value.
338
  ///
339
  /// Defaults to [SliderTheme.activeTrackColor] of the current [SliderTheme].
340 341 342 343
  ///
  /// Using a [SliderTheme] gives much more fine-grained control over the
  /// appearance of various components of the slider.
  final Color activeColor;
344

345
  /// The color for the inactive portion of the slider track.
346
  ///
347 348
  /// The "inactive" side of the slider is the side between the thumb and the
  /// maximum value.
349
  ///
350
  /// Defaults to the [SliderTheme.inactiveTrackColor] of the current
351
  /// [SliderTheme].
352
  ///
353 354
  /// Using a [SliderTheme] gives much more fine-grained control over the
  /// appearance of various components of the slider.
355 356
  ///
  /// Ignored if this slider is created with [Slider.adaptive].
357
  final Color inactiveColor;
358

359 360 361 362 363 364 365
  /// 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.
  ///
366
  /// {@tool snippet}
367 368 369 370 371
  ///
  /// In the example below, a slider for currency values is configured to
  /// announce a value with a currency label.
  ///
  /// ```dart
372
  /// Slider(
373 374 375 376 377 378 379 380 381 382 383 384 385 386
  ///   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';
  ///   }
  ///  )
  /// ```
387
  /// {@end-tool}
388 389
  ///
  /// Ignored if this slider is created with [Slider.adaptive]
390 391
  final SemanticFormatterCallback semanticFormatterCallback;

392 393 394 395 396 397
  /// {@macro flutter.widgets.Focus.focusNode}
  final FocusNode focusNode;

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

398 399 400 401 402 403 404 405 406 407 408 409 410 411
  /// Whether to use the updated Material spec version of the [Slider].
  ///
  /// * The v2 Slider has an updated value indicator that matches the latest specs.
  /// * The value indicator is painted on the Overlay.
  /// * The active track is bigger than the inactive track.
  /// * The thumb that is activated has elevation.
  /// * Updated value indicators in case they overlap with each other.
  /// * <https://groups.google.com/g/flutter-announce/c/69dmlKUL5Ew/m/tQh-ajiEAAAJl>
  ///
  /// This is a temporary flag for migrating the slider from v1 to v2. To avoid
  /// unexpected breaking changes, this value should be set to true. Setting
  /// this to false is considered deprecated.
  final bool useV2Slider;

412 413
  final _SliderType _sliderType ;

414
  @override
415
  _SliderState createState() => _SliderState();
416 417

  @override
418 419
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
420
    properties.add(DoubleProperty('value', value));
421 422 423
    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));
424 425
    properties.add(DoubleProperty('min', min));
    properties.add(DoubleProperty('max', max));
426 427 428 429 430
    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));
431 432 433
    properties.add(ObjectFlagProperty<FocusNode>.has('focusNode', focusNode));
    properties.add(FlagProperty('autofocus', value: autofocus, ifTrue: 'autofocus'));
    properties.add(FlagProperty('useV2Slider', value: useV2Slider, ifFalse: 'useV1Slider'));
434
  }
435 436 437
}

class _SliderState extends State<Slider> with TickerProviderStateMixin {
438 439
  static const Duration enableAnimationDuration = Duration(milliseconds: 75);
  static const Duration valueIndicatorAnimationDuration = Duration(milliseconds: 100);
440 441 442 443 444 445 446

  // 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;
447
  // Animation controller that is run when enabling/disabling the slider.
448
  AnimationController enableController;
449 450
  // Animation controller that is run when transitioning between one value
  // and the next on a discrete slider.
451
  AnimationController positionController;
452
  Timer interactionTimer;
453 454 455 456 457 458 459 460

  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;
461 462
  // Value Indicator Animation that appears on the Overlay.
  PaintValueIndicator paintValueIndicator;
463 464 465 466

  @override
  void initState() {
    super.initState();
467
    overlayController = AnimationController(
468 469 470
      duration: kRadialReactionDuration,
      vsync: this,
    );
471
    valueIndicatorController = AnimationController(
472 473 474
      duration: valueIndicatorAnimationDuration,
      vsync: this,
    );
475
    enableController = AnimationController(
476 477 478
      duration: enableAnimationDuration,
      vsync: this,
    );
479
    positionController = AnimationController(
480
      duration: Duration.zero,
481 482
      vsync: this,
    );
483
    enableController.value = widget.onChanged != null ? 1.0 : 0.0;
484
    positionController.value = _unlerp(widget.value);
485 486 487 488 489 490 491 492 493 494 495
    _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,
      ),
    };
496 497 498 499
  }

  @override
  void dispose() {
500
    interactionTimer?.cancel();
501 502
    overlayController.dispose();
    valueIndicatorController.dispose();
503 504 505
    enableController.dispose();
    positionController.dispose();
    super.dispose();
506 507
  }

Hixie's avatar
Hixie committed
508
  void _handleChanged(double value) {
509
    assert(widget.onChanged != null);
510 511 512 513
    final double lerpValue = _lerp(value);
    if (lerpValue != widget.value) {
      widget.onChanged(lerpValue);
    }
Hixie's avatar
Hixie committed
514 515
  }

516 517 518 519 520 521 522 523 524 525
  void _handleDragStart(double value) {
    assert(widget.onChangeStart != null);
    widget.onChangeStart(_lerp(value));
  }

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

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
  void _actionHandler (_AdjustSliderIntent intent) {
    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; });
    }
  }

573 574 575 576 577 578
  // 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;
579 580
  }

581 582 583 584
  // 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);
585
    return widget.max > widget.min ? (value - widget.min) / (widget.max - widget.min) : 0.0;
586
  }
587

588
  @override
589
  Widget build(BuildContext context) {
590
    assert(debugCheckHasMaterial(context));
591
    assert(debugCheckHasMediaQuery(context));
592

593 594 595 596 597 598 599 600 601 602
    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:
603 604
          case TargetPlatform.linux:
          case TargetPlatform.windows:
605 606
            return _buildMaterialSlider(context);
          case TargetPlatform.iOS:
607
          case TargetPlatform.macOS:
608 609 610 611 612 613 614 615 616
            return _buildCupertinoSlider(context);
        }
      }
    }
    assert(false);
    return null;
  }

  Widget _buildMaterialSlider(BuildContext context) {
617
    final ThemeData theme = Theme.of(context);
618 619 620 621
    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
622 623 624 625
    // 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.
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647

    final bool useV2Slider = widget.useV2Slider;
    final double _defaultTrackHeight = useV2Slider ? 4 : 2;
    final SliderTrackShape _defaultTrackShape = RoundedRectSliderTrackShape(useV2Slider: useV2Slider);
    final SliderTickMarkShape _defaultTickMarkShape = RoundSliderTickMarkShape(useV2Slider: useV2Slider);
    const SliderComponentShape _defaultOverlayShape = RoundSliderOverlayShape();
    final SliderComponentShape _defaultThumbShape = RoundSliderThumbShape(useV2Slider: useV2Slider);
    final SliderComponentShape _defaultValueIndicatorShape = useV2Slider ? const RectangularSliderValueIndicatorShape() : const PaddleSliderValueIndicatorShape();
    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;
    }

648 649 650 651 652 653 654 655 656 657 658
    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,
659
      disabledThumbColor: sliderTheme.disabledThumbColor ?? Color.alphaBlend(theme.colorScheme.onSurface.withOpacity(.38), theme.colorScheme.surface),
660
      overlayColor: widget.activeColor?.withOpacity(0.12) ?? sliderTheme.overlayColor ?? theme.colorScheme.primary.withOpacity(0.12),
661
      valueIndicatorColor: valueIndicatorColor,
662 663 664 665
      trackShape: sliderTheme.trackShape ?? _defaultTrackShape,
      tickMarkShape: sliderTheme.tickMarkShape ?? _defaultTickMarkShape,
      thumbShape: sliderTheme.thumbShape ?? _defaultThumbShape,
      overlayShape: sliderTheme.overlayShape ?? _defaultOverlayShape,
666
      valueIndicatorShape: valueIndicatorShape,
667
      showValueIndicator: sliderTheme.showValueIndicator ?? _defaultShowValueIndicator,
668
      valueIndicatorTextStyle: sliderTheme.valueIndicatorTextStyle ?? theme.textTheme.bodyText1.copyWith(
669 670 671
        color: theme.colorScheme.onPrimary,
      ),
    );
672

673 674 675 676 677
    // 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;

678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
    return FocusableActionDetector(
      actions: _actionMap,
      shortcuts: _shortcutMap,
      focusNode: widget.focusNode,
      autofocus: widget.autofocus,
      enabled: _enabled,
      onShowFocusHighlight: _handleFocusHighlightChanged,
      onShowHoverHighlight: _handleHoverChanged,
      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,
          useV2Slider: widget.useV2Slider,
        ),
705
      ),
706 707
    );
  }
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726

  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,
      ),
    );
  }
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
  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);
    }
  }
746 747
}

748

749
class _SliderRenderObjectWidget extends LeafRenderObjectWidget {
750
  const _SliderRenderObjectWidget({
751 752 753 754
    Key key,
    this.value,
    this.divisions,
    this.label,
755
    this.sliderTheme,
756 757
    this.textScaleFactor,
    this.screenSize,
758
    this.onChanged,
759 760
    this.onChangeStart,
    this.onChangeEnd,
761
    this.state,
762
    this.semanticFormatterCallback,
763 764
    this.hasFocus,
    this.hovering,
765
    this.useV2Slider,
766
  }) : super(key: key);
767 768

  final double value;
769 770
  final int divisions;
  final String label;
771
  final SliderThemeData sliderTheme;
772 773
  final double textScaleFactor;
  final Size screenSize;
774
  final ValueChanged<double> onChanged;
775 776
  final ValueChanged<double> onChangeStart;
  final ValueChanged<double> onChangeEnd;
777
  final SemanticFormatterCallback semanticFormatterCallback;
778
  final _SliderState state;
779 780
  final bool hasFocus;
  final bool hovering;
781
  final bool useV2Slider;
782

783
  @override
784
  _RenderSlider createRenderObject(BuildContext context) {
785
    return _RenderSlider(
786 787 788
      value: value,
      divisions: divisions,
      label: label,
789
      sliderTheme: sliderTheme,
790 791
      textScaleFactor: textScaleFactor,
      screenSize: screenSize,
792
      onChanged: onChanged,
793 794
      onChangeStart: onChangeStart,
      onChangeEnd: onChangeEnd,
795
      state: state,
796
      textDirection: Directionality.of(context),
797 798
      semanticFormatterCallback: semanticFormatterCallback,
      platform: Theme.of(context).platform,
799 800
      hasFocus: hasFocus,
      hovering: hovering,
801
      useV2Slider: useV2Slider,
802 803
    );
  }
804

805
  @override
806
  void updateRenderObject(BuildContext context, _RenderSlider renderObject) {
807 808
    renderObject
      ..value = value
809 810
      ..divisions = divisions
      ..label = label
811 812
      ..sliderTheme = sliderTheme
      ..theme = Theme.of(context)
813 814
      ..textScaleFactor = textScaleFactor
      ..screenSize = screenSize
815
      ..onChanged = onChanged
816 817
      ..onChangeStart = onChangeStart
      ..onChangeEnd = onChangeEnd
818 819
      ..textDirection = Directionality.of(context)
      ..semanticFormatterCallback = semanticFormatterCallback
820 821 822
      ..platform = Theme.of(context).platform
      ..hasFocus = hasFocus
      ..hovering = hovering;
823 824
    // Ticker provider cannot change since there's a 1:1 relationship between
    // the _SliderRenderObjectWidget object and the _SliderState object.
825 826 827
  }
}

828
class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
829
  _RenderSlider({
830
    @required double value,
831 832
    int divisions,
    String label,
833
    SliderThemeData sliderTheme,
834 835
    double textScaleFactor,
    Size screenSize,
836
    TargetPlatform platform,
837
    ValueChanged<double> onChanged,
838
    SemanticFormatterCallback semanticFormatterCallback,
839 840
    this.onChangeStart,
    this.onChangeEnd,
841
    @required _SliderState state,
842
    @required TextDirection textDirection,
843 844
    bool hasFocus,
    bool hovering,
845
    bool useV2Slider,
846
  }) : assert(value != null && value >= 0.0 && value <= 1.0),
847 848 849 850 851 852 853 854 855 856 857 858 859
        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,
860 861
        _hasFocus = hasFocus,
        _hovering = hovering,
862
        _useV2Slider = useV2Slider {
Ian Hickson's avatar
Ian Hickson committed
863
    _updateLabelPainter();
864 865
    final GestureArenaTeam team = GestureArenaTeam();
    _drag = HorizontalDragGestureRecognizer()
866
      ..team = team
867 868
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
869 870
      ..onEnd = _handleDragEnd
      ..onCancel = _endInteraction;
871
    _tap = TapGestureRecognizer()
872
      ..team = team
873
      ..onTapDown = _handleTapDown
874 875
      ..onTapUp = _handleTapUp
      ..onTapCancel = _endInteraction;
876
    _overlayAnimation = CurvedAnimation(
877 878 879
      parent: _state.overlayController,
      curve: Curves.fastOutSlowIn,
    );
880
    _valueIndicatorAnimation = CurvedAnimation(
881
      parent: _state.valueIndicatorController,
882
      curve: Curves.fastOutSlowIn,
883 884 885 886 887 888
    )..addStatusListener((AnimationStatus status) {
      if (status == AnimationStatus.dismissed && _state.overlayEntry != null) {
        _state.overlayEntry.remove();
        _state.overlayEntry = null;
      }
    });
889
    _enableAnimation = CurvedAnimation(
890 891 892
      parent: _state.enableController,
      curve: Curves.easeInOut,
    );
893
  }
894 895
  static const Duration _positionAnimationDuration = Duration(milliseconds: 75);
  static const Duration _minimumInteractionTime = Duration(milliseconds: 500);
896 897 898 899 900 901 902 903

  // 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);
904
  double get _maxSliderPartHeight => _sliderPartSizes.map((Size size) => size.height).reduce(math.max);
905 906 907 908 909
  List<Size> get _sliderPartSizes => <Size>[
    _sliderTheme.overlayShape.getPreferredSize(isInteractive, isDiscrete),
    _sliderTheme.thumbShape.getPreferredSize(isInteractive, isDiscrete),
    _sliderTheme.tickMarkShape.getPreferredSize(isEnabled: isInteractive, sliderTheme: sliderTheme),
  ];
910
  double get _minPreferredTrackHeight => _sliderTheme.trackHeight;
911

912
  final _SliderState _state;
913 914 915
  Animation<double> _overlayAnimation;
  Animation<double> _valueIndicatorAnimation;
  Animation<double> _enableAnimation;
916
  final TextPainter _labelPainter = TextPainter();
917 918 919 920 921
  HorizontalDragGestureRecognizer _drag;
  TapGestureRecognizer _tap;
  bool _active = false;
  double _currentDragValue = 0.0;

922 923 924 925 926 927 928 929 930
  // 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,
  );
931 932 933 934

  bool get isInteractive => onChanged != null;

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

936 937
  double get value => _value;
  double _value;
938
  set value(double newValue) {
939
    assert(newValue != null && newValue >= 0.0 && newValue <= 1.0);
940 941
    final double convertedValue = isDiscrete ? _discretize(newValue) : newValue;
    if (convertedValue == _value) {
942
      return;
943 944 945
    }
    _value = convertedValue;
    if (isDiscrete) {
946 947 948 949 950 951 952
      // 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)
953
        : Duration.zero;
954 955 956 957
      _state.positionController.animateTo(convertedValue, curve: Curves.easeInOut);
    } else {
      _state.positionController.value = convertedValue;
    }
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
    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();
977 978 979 980
  }

  int get divisions => _divisions;
  int _divisions;
981
  set divisions(int value) {
982
    if (value == _divisions) {
983
      return;
984
    }
985
    _divisions = value;
986 987 988 989 990
    markNeedsPaint();
  }

  String get label => _label;
  String _label;
991
  set label(String value) {
992
    if (value == _label) {
993
      return;
994
    }
995
    _label = value;
Ian Hickson's avatar
Ian Hickson committed
996
    _updateLabelPainter();
997 998
  }

999 1000 1001 1002
  SliderThemeData get sliderTheme => _sliderTheme;
  SliderThemeData _sliderTheme;
  set sliderTheme(SliderThemeData value) {
    if (value == _sliderTheme) {
1003
      return;
1004 1005
    }
    _sliderTheme = value;
1006 1007 1008
    markNeedsPaint();
  }

1009 1010 1011 1012
  ThemeData get theme => _theme;
  ThemeData _theme;
  set theme(ThemeData value) {
    if (value == _theme) {
1013
      return;
1014 1015
    }
    _theme = value;
1016 1017 1018
    markNeedsPaint();
  }

1019 1020 1021 1022
  double get textScaleFactor => _textScaleFactor;
  double _textScaleFactor;
  set textScaleFactor(double value) {
    if (value == _textScaleFactor) {
1023
      return;
1024
    }
1025
    _textScaleFactor = value;
1026 1027 1028
    _updateLabelPainter();
  }

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
  Size get screenSize => _screenSize;
  Size _screenSize;
  set screenSize(Size value) {
    if (value == _screenSize) {
      return;
    }
    _screenSize = value;
    markNeedsPaint();
  }

1039 1040 1041
  ValueChanged<double> get onChanged => _onChanged;
  ValueChanged<double> _onChanged;
  set onChanged(ValueChanged<double> value) {
1042
    if (value == _onChanged) {
1043
      return;
1044
    }
1045 1046 1047
    final bool wasInteractive = isInteractive;
    _onChanged = value;
    if (wasInteractive != isInteractive) {
1048 1049 1050 1051 1052
      if (isInteractive) {
        _state.enableController.forward();
      } else {
        _state.enableController.reverse();
      }
1053
      markNeedsPaint();
1054
      markNeedsSemanticsUpdate();
1055 1056
    }
  }
1057

1058 1059 1060
  ValueChanged<double> onChangeStart;
  ValueChanged<double> onChangeEnd;

1061 1062 1063 1064
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    assert(value != null);
1065
    if (value == _textDirection) {
1066
      return;
1067
    }
1068
    _textDirection = value;
Ian Hickson's avatar
Ian Hickson committed
1069 1070 1071
    _updateLabelPainter();
  }

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  /// 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);
  }

  /// 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();
      }
    }
  }
1107 1108
  final bool _useV2Slider;

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
  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;
  }

1128 1129 1130
  double get _adjustmentUnit {
    switch (_platform) {
      case TargetPlatform.iOS:
1131
      case TargetPlatform.macOS:
1132
        // Matches iOS implementation of material slider.
1133 1134 1135
        return 0.1;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
1136 1137 1138
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        // Matches Android implementation of material slider.
1139 1140
        return 0.05;
    }
1141
    assert(false, 'Unhandled TargetPlatform $_platform');
1142
    return 0.0;
1143 1144
  }

Ian Hickson's avatar
Ian Hickson committed
1145 1146 1147
  void _updateLabelPainter() {
    if (label != null) {
      _labelPainter
1148
        ..text = TextSpan(
1149 1150 1151
          style: _sliderTheme.valueIndicatorTextStyle,
          text: label,
        )
Ian Hickson's avatar
Ian Hickson committed
1152
        ..textDirection = textDirection
1153
        ..textScaleFactor = textScaleFactor
Ian Hickson's avatar
Ian Hickson committed
1154 1155 1156 1157 1158 1159 1160 1161
        ..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();
1162 1163
  }

1164 1165 1166 1167 1168 1169 1170
  @override
  void systemFontsDidChange() {
    super.systemFontsDidChange();
    _labelPainter.markNeedsLayout();
    _updateLabelPainter();
  }

1171 1172 1173
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
1174 1175
    _overlayAnimation.addListener(markNeedsPaint);
    _valueIndicatorAnimation.addListener(markNeedsPaint);
1176 1177 1178 1179 1180 1181
    _enableAnimation.addListener(markNeedsPaint);
    _state.positionController.addListener(markNeedsPaint);
  }

  @override
  void detach() {
1182 1183
    _overlayAnimation.removeListener(markNeedsPaint);
    _valueIndicatorAnimation.removeListener(markNeedsPaint);
1184 1185 1186 1187 1188
    _enableAnimation.removeListener(markNeedsPaint);
    _state.positionController.removeListener(markNeedsPaint);
    super.detach();
  }

1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
  double _getValueFromVisualPosition(double visualPosition) {
    switch (textDirection) {
      case TextDirection.rtl:
        return 1.0 - visualPosition;
      case TextDirection.ltr:
        return visualPosition;
    }
    return null;
  }

1199
  double _getValueFromGlobalPosition(Offset globalPosition) {
1200
    final double visualPosition = (globalToLocal(globalPosition).dx - _trackRect.left) / _trackRect.width;
1201
    return _getValueFromVisualPosition(visualPosition);
1202 1203
  }

1204
  double _discretize(double value) {
1205
    double result = value.clamp(0.0, 1.0) as double;
1206
    if (isDiscrete) {
1207
      result = (result * divisions).round() / divisions;
1208
    }
1209 1210
    return result;
  }
1211

1212
  void _startInteraction(Offset globalPosition) {
1213
    _state.showValueIndicator();
1214
    if (isInteractive) {
1215
      _active = true;
1216 1217 1218 1219 1220 1221
      // 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));
      }
1222
      _currentDragValue = _getValueFromGlobalPosition(globalPosition);
1223
      onChanged(_discretize(_currentDragValue));
1224 1225 1226
      _state.overlayController.forward();
      if (showValueIndicator) {
        _state.valueIndicatorController.forward();
1227
        _state.interactionTimer?.cancel();
1228
        _state.interactionTimer = Timer(_minimumInteractionTime * timeDilation, () {
1229 1230 1231
          _state.interactionTimer = null;
          if (!_active &&
              _state.valueIndicatorController.status == AnimationStatus.completed) {
1232 1233 1234 1235
            _state.valueIndicatorController.reverse();
          }
        });
      }
1236 1237 1238 1239
    }
  }

  void _endInteraction() {
1240
    if (_active && _state.mounted) {
1241 1242 1243
      if (onChangeEnd != null) {
        onChangeEnd(_discretize(_currentDragValue));
      }
1244 1245
      _active = false;
      _currentDragValue = 0.0;
1246
      _state.overlayController.reverse();
1247

1248
      if (showValueIndicator && _state.interactionTimer == null) {
1249 1250
        _state.valueIndicatorController.reverse();
      }
1251 1252 1253
    }
  }

1254 1255
  void _handleDragStart(DragStartDetails details) => _startInteraction(details.globalPosition);

1256
  void _handleDragUpdate(DragUpdateDetails details) {
1257
    if (isInteractive) {
1258
      final double valueDelta = details.primaryDelta / _trackRect.width;
1259 1260 1261 1262 1263 1264 1265 1266
      switch (textDirection) {
        case TextDirection.rtl:
          _currentDragValue -= valueDelta;
          break;
        case TextDirection.ltr:
          _currentDragValue += valueDelta;
          break;
      }
1267
      onChanged(_discretize(_currentDragValue));
1268 1269 1270
    }
  }

1271
  void _handleDragEnd(DragEndDetails details) => _endInteraction();
1272

1273 1274 1275
  void _handleTapDown(TapDownDetails details) => _startInteraction(details.globalPosition);

  void _handleTapUp(TapUpDetails details) => _endInteraction();
1276

1277
  @override
1278
  bool hitTestSelf(Offset position) => true;
1279

1280
  @override
Ian Hickson's avatar
Ian Hickson committed
1281
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
1282
    assert(debugHandleEvent(event, entry));
1283 1284
    if (event is PointerDownEvent && isInteractive) {
      // We need to add the drag first so that it has priority.
1285
      _drag.addPointer(event);
1286 1287
      _tap.addPointer(event);
    }
1288 1289
  }

1290
  @override
1291
  double computeMinIntrinsicWidth(double height) => _minPreferredTrackWidth + _maxSliderPartWidth;
1292 1293

  @override
1294
  double computeMaxIntrinsicWidth(double height) => _minPreferredTrackWidth + _maxSliderPartWidth;
1295 1296

  @override
1297
  double computeMinIntrinsicHeight(double width) => max(_minPreferredTrackHeight, _maxSliderPartHeight);
1298 1299

  @override
1300
  double computeMaxIntrinsicHeight(double width) => max(_minPreferredTrackHeight, _maxSliderPartHeight);
1301 1302 1303 1304 1305 1306

  @override
  bool get sizedByParent => true;

  @override
  void performResize() {
1307
    size = Size(
1308 1309
      constraints.hasBoundedWidth ? constraints.maxWidth : _minPreferredTrackWidth + _maxSliderPartWidth,
      constraints.hasBoundedHeight ? constraints.maxHeight : max(_minPreferredTrackHeight, _maxSliderPartHeight),
1310 1311 1312
    );
  }

1313
  @override
1314
  void paint(PaintingContext context, Offset offset) {
1315
    final double value = _state.positionController.value;
1316

1317 1318 1319
    // 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.
1320 1321 1322 1323 1324 1325 1326 1327 1328
    double visualPosition;
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - value;
        break;
      case TextDirection.ltr:
        visualPosition = value;
        break;
    }
1329

1330 1331 1332 1333
    final Rect trackRect = _sliderTheme.trackShape.getPreferredRect(
      parentBox: this,
      offset: offset,
      sliderTheme: _sliderTheme,
1334
      isDiscrete: isDiscrete,
1335
    );
1336
    final Offset thumbCenter = Offset(trackRect.left + visualPosition * trackRect.width, trackRect.center.dy);
1337

1338 1339 1340 1341 1342 1343 1344 1345 1346
    _sliderTheme.trackShape.paint(
      context,
      offset,
      parentBox: this,
      sliderTheme: _sliderTheme,
      enableAnimation: _enableAnimation,
      textDirection: _textDirection,
      thumbCenter: thumbCenter,
      isDiscrete: isDiscrete,
1347
      isEnabled: isInteractive,
1348 1349
    );

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
    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;
1370 1371
      final double padding = _useV2Slider ? trackRect.height : tickMarkWidth;
      final double adjustedTrackWidth = trackRect.width - padding;
1372 1373 1374
      // 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;
1375
        for (int i = 0; i <= divisions; i++) {
1376
          final double value = i / divisions;
1377 1378
          // The ticks are mapped to be within the track, so the tick mark width
          // must be subtracted from the track width.
1379
          final double dx = trackRect.left + value * adjustedTrackWidth + padding / 2;
1380
          final Offset tickMarkOffset = Offset(dx, dy);
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
          _sliderTheme.tickMarkShape.paint(
            context,
            tickMarkOffset,
            parentBox: this,
            sliderTheme: _sliderTheme,
            enableAnimation: _enableAnimation,
            textDirection: _textDirection,
            thumbCenter: thumbCenter,
            isEnabled: isInteractive,
          );
        }
1392 1393 1394 1395
      }
    }

    if (isInteractive && label != null && !_valueIndicatorAnimation.isDismissed) {
1396
      if (showValueIndicator) {
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
        _state.paintValueIndicator = (PaintingContext context, Offset offset) {
          _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,
          );
        };
1413
      }
1414
    }
Adam Barth's avatar
Adam Barth committed
1415

1416 1417 1418
    _sliderTheme.thumbShape.paint(
      context,
      thumbCenter,
1419
      activationAnimation: _overlayAnimation,
1420 1421 1422 1423 1424 1425
      enableAnimation: _enableAnimation,
      isDiscrete: isDiscrete,
      labelPainter: _labelPainter,
      parentBox: this,
      sliderTheme: _sliderTheme,
      textDirection: _textDirection,
1426
      sizeWithOverflow: screenSize.isEmpty ? size : screenSize,
1427
      value: _value,
1428
    );
1429
  }
1430 1431

  @override
1432 1433
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
1434

1435 1436
    config.isSemanticBoundary = isInteractive;
    if (isInteractive) {
1437
      config.textDirection = textDirection;
1438 1439
      config.onIncrease = increaseAction;
      config.onDecrease = decreaseAction;
1440 1441
      if (semanticFormatterCallback != null) {
        config.value = semanticFormatterCallback(_state._lerp(value));
1442 1443
        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));
1444 1445 1446 1447 1448
      } 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()}%';
      }
1449 1450 1451
    }
  }

1452
  double get _semanticActionUnit => divisions != null ? 1.0 / divisions : _adjustmentUnit;
1453

1454
  void increaseAction() {
1455
    if (isInteractive) {
1456
      onChanged((value + _semanticActionUnit).clamp(0.0, 1.0) as double);
1457
    }
1458 1459
  }

1460
  void decreaseAction() {
1461
    if (isInteractive) {
1462
      onChanged((value - _semanticActionUnit).clamp(0.0, 1.0) as double);
1463
    }
1464
  }
1465
}
1466

1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
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,
}

1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
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);
    }
  }
}