slider.dart 53.6 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 7
import 'dart:math' as math;

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

15
import 'constants.dart';
16
import 'debug.dart';
17
import 'material.dart';
18
import 'material_state.dart';
19
import 'slider_theme.dart';
20 21
import 'theme.dart';

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

27 28 29 30 31 32
/// [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);

33 34
enum _SliderType { material, adaptive }

35
/// A Material Design slider.
36
///
37 38
/// Used to select from a range of values.
///
39 40
/// {@youtube 560 315 https://www.youtube.com/watch?v=ufb4gIPDmEs}
///
41
/// {@tool dartpad --template=stateful_widget_scaffold}
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
///
/// ![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}
///
70
/// A slider can be used to select from either a continuous or a discrete set of
71 72
/// 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
73
/// indicates the number of discrete intervals. For example, if [min] is 0.0 and
74
/// [max] is 50.0 and [divisions] is 5, then the slider can take on the
75
/// discrete values 0.0, 10.0, 20.0, 30.0, 40.0, and 50.0.
76
///
77 78 79 80
/// The terms for the parts of a slider are:
///
///  * The "thumb", which is a shape that slides horizontally when the user
///    drags it.
81
///  * The "track", which is the line that the slider thumb slides along.
82 83 84 85 86 87 88
///  * 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.
///
89 90 91
/// 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]).
///
92 93 94 95
/// 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
96 97
/// slider. To know when the value starts to change, or when it is done
/// changing, set the optional callbacks [onChangeStart] and/or [onChangeEnd].
98
///
99
/// By default, a slider will be as wide as possible, centered vertically. When
100
/// given unbounded constraints, it will attempt to make the track 144 pixels
101
/// wide (with margins on each side) and will shrink-wrap vertically.
102
///
103 104
/// Requires one of its ancestors to be a [Material] widget.
///
105 106 107 108
/// 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.
///
109 110 111 112 113 114 115
/// 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].
///
116
/// See also:
117
///
118 119
///  * [SliderTheme] and [SliderThemeData] for information about controlling
///    the visual appearance of the slider.
120 121
///  * [Radio], for selecting among a set of explicit values.
///  * [Checkbox] and [Switch], for toggling a particular value on or off.
122
///  * <https://material.io/design/components/sliders.html>
123
///  * [MediaQuery], from which the text scale factor is obtained.
124
class Slider extends StatefulWidget {
125
  /// Creates a Material Design slider.
126 127
  ///
  /// The slider itself does not maintain any state. Instead, when the state of
128 129 130 131
  /// 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.
132 133
  ///
  /// * [value] determines currently selected value for this slider.
134 135 136 137 138 139
  /// * [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.
140 141 142 143
  ///
  /// 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].
144
  const Slider({
145 146 147
    Key? key,
    required this.value,
    required this.onChanged,
148 149
    this.onChangeStart,
    this.onChangeEnd,
150 151
    this.min = 0.0,
    this.max = 1.0,
152 153
    this.divisions,
    this.label,
154
    this.activeColor,
155
    this.inactiveColor,
156
    this.thumbColor,
157
    this.mouseCursor,
158
    this.semanticFormatterCallback,
159 160
    this.focusNode,
    this.autofocus = false,
161 162 163 164 165 166 167 168 169
  }) : _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);

170 171 172 173
  /// Creates an adaptive [Slider] based on the target platform, following
  /// Material design's
  /// [Cross-platform guidelines](https://material.io/design/platform-guidance/cross-platform-adaptation.html).
  ///
174 175 176 177 178 179 180 181
  /// 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({
182 183 184
    Key? key,
    required this.value,
    required this.onChanged,
185 186 187 188 189 190
    this.onChangeStart,
    this.onChangeEnd,
    this.min = 0.0,
    this.max = 1.0,
    this.divisions,
    this.label,
191
    this.mouseCursor,
192 193
    this.activeColor,
    this.inactiveColor,
194
    this.thumbColor,
195
    this.semanticFormatterCallback,
196 197
    this.focusNode,
    this.autofocus = false,
198 199
  }) : _sliderType = _SliderType.adaptive,
       assert(value != null),
200 201
       assert(min != null),
       assert(max != null),
202
       assert(min <= max),
203 204 205
       assert(value >= min && value <= max),
       assert(divisions == null || divisions > 0),
       super(key: key);
206

207 208 209
  /// The currently selected value for this slider.
  ///
  /// The slider's thumb is drawn at a position that corresponds to this value.
210
  final double value;
211

212 213
  /// Called during a drag when the user is selecting a new value for the slider
  /// by dragging.
214 215 216 217 218 219
  ///
  /// 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.
220 221 222 223 224
  ///
  /// 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:
  ///
225
  /// {@tool snippet}
226
  ///
227
  /// ```dart
228
  /// Slider(
229 230 231 232 233 234 235 236 237 238
  ///   value: _duelCommandment.toDouble(),
  ///   min: 1.0,
  ///   max: 10.0,
  ///   divisions: 10,
  ///   label: '$_duelCommandment',
  ///   onChanged: (double newValue) {
  ///     setState(() {
  ///       _duelCommandment = newValue.round();
  ///     });
  ///   },
239
  /// )
240
  /// ```
241
  /// {@end-tool}
242 243 244 245 246 247 248
  ///
  /// 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.
249
  final ValueChanged<double>? onChanged;
250

251 252 253 254 255 256 257 258 259
  /// 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.
  ///
260
  /// {@tool snippet}
261 262
  ///
  /// ```dart
263
  /// Slider(
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
  ///   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');
  ///   },
  /// )
  /// ```
279
  /// {@end-tool}
280 281 282 283 284
  ///
  /// See also:
  ///
  ///  * [onChangeEnd] for a callback that is called when the value change is
  ///    complete.
285
  final ValueChanged<double>? onChangeStart;
286 287 288 289 290 291 292

  /// 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.
  ///
293
  /// {@tool snippet}
294 295
  ///
  /// ```dart
296
  /// Slider(
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
  ///   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');
  ///   },
  /// )
  /// ```
312
  /// {@end-tool}
313 314 315 316 317
  ///
  /// See also:
  ///
  ///  * [onChangeStart] for a callback that is called when a value change
  ///    begins.
318
  final ValueChanged<double>? onChangeEnd;
319

320
  /// The minimum value the user can select.
321
  ///
322 323 324
  /// 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
325
  final double min;
326 327 328

  /// The maximum value the user can select.
  ///
329 330 331
  /// 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
332
  final double max;
333

334 335 336 337 338
  /// The number of discrete divisions.
  ///
  /// Typically used with [label] to show the current discrete value.
  ///
  /// If null, the slider is continuous.
339
  final int? divisions;
340 341 342

  /// A label to show above the slider when the slider is active.
  ///
343 344 345
  /// It is used to display the value of a discrete slider, and it is displayed
  /// as part of the value indicator shape.
  ///
346 347 348 349
  /// 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].
350 351 352
  ///
  /// If null, then the value indicator will not be displayed.
  ///
353 354
  /// Ignored if this slider is created with [Slider.adaptive].
  ///
355 356 357 358
  /// See also:
  ///
  ///  * [SliderComponentShape] for how to create a custom value indicator
  ///    shape.
359
  final String? label;
360

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

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

387 388 389 390 391 392 393 394
  /// The color of the thumb.
  ///
  /// If this color is null:
  /// * [Slider] will use [activeColor].
  /// * [CupertinoSlider] will have a white thumb
  /// (like the native default iOS slider).
  final Color? thumbColor;

395 396 397 398 399 400 401 402 403 404 405
  /// 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.
406
  final MouseCursor? mouseCursor;
407

408 409 410 411 412 413 414
  /// 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.
  ///
415
  /// {@tool snippet}
416 417 418 419 420
  ///
  /// In the example below, a slider for currency values is configured to
  /// announce a value with a currency label.
  ///
  /// ```dart
421
  /// Slider(
422 423 424 425 426 427 428 429 430 431 432 433 434 435
  ///   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';
  ///   }
  ///  )
  /// ```
436
  /// {@end-tool}
437 438
  ///
  /// Ignored if this slider is created with [Slider.adaptive]
439
  final SemanticFormatterCallback? semanticFormatterCallback;
440

441
  /// {@macro flutter.widgets.Focus.focusNode}
442
  final FocusNode? focusNode;
443 444 445 446

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

447 448
  final _SliderType _sliderType ;

449
  @override
450
  State<Slider> createState() => _SliderState();
451 452

  @override
453 454
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
455
    properties.add(DoubleProperty('value', value));
456 457 458
    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));
459 460
    properties.add(DoubleProperty('min', min));
    properties.add(DoubleProperty('max', max));
461 462 463 464 465
    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));
466 467
    properties.add(ObjectFlagProperty<FocusNode>.has('focusNode', focusNode));
    properties.add(FlagProperty('autofocus', value: autofocus, ifTrue: 'autofocus'));
468
  }
469 470 471
}

class _SliderState extends State<Slider> with TickerProviderStateMixin {
472 473
  static const Duration enableAnimationDuration = Duration(milliseconds: 75);
  static const Duration valueIndicatorAnimationDuration = Duration(milliseconds: 100);
474 475 476

  // Animation controller that is run when the overlay (a.k.a radial reaction)
  // is shown in response to user interaction.
477
  late AnimationController overlayController;
478 479
  // Animation controller that is run when the value indicator is being shown
  // or hidden.
480
  late AnimationController valueIndicatorController;
481
  // Animation controller that is run when enabling/disabling the slider.
482
  late AnimationController enableController;
483 484
  // Animation controller that is run when transitioning between one value
  // and the next on a discrete slider.
485 486
  late AnimationController positionController;
  Timer? interactionTimer;
487 488 489

  final GlobalKey _renderObjectKey = GlobalKey();
  // Keyboard mapping for a focused slider.
490 491 492 493 494 495
  final Map<ShortcutActivator, Intent> _shortcutMap = const <ShortcutActivator, Intent>{
      SingleActivator(LogicalKeyboardKey.arrowUp): _AdjustSliderIntent.up(),
      SingleActivator(LogicalKeyboardKey.arrowDown): _AdjustSliderIntent.down(),
      SingleActivator(LogicalKeyboardKey.arrowLeft): _AdjustSliderIntent.left(),
      SingleActivator(LogicalKeyboardKey.arrowRight): _AdjustSliderIntent.right(),
    };
496
  // Action mapping for a focused slider.
497
  late Map<Type, Action<Intent>> _actionMap;
498 499

  bool get _enabled => widget.onChanged != null;
500
  // Value Indicator Animation that appears on the Overlay.
501
  PaintValueIndicator? paintValueIndicator;
502 503 504 505

  @override
  void initState() {
    super.initState();
506
    overlayController = AnimationController(
507 508 509
      duration: kRadialReactionDuration,
      vsync: this,
    );
510
    valueIndicatorController = AnimationController(
511 512 513
      duration: valueIndicatorAnimationDuration,
      vsync: this,
    );
514
    enableController = AnimationController(
515 516 517
      duration: enableAnimationDuration,
      vsync: this,
    );
518
    positionController = AnimationController(
519
      duration: Duration.zero,
520 521
      vsync: this,
    );
522
    enableController.value = widget.onChanged != null ? 1.0 : 0.0;
523
    positionController.value = _unlerp(widget.value);
524 525 526 527 528
    _actionMap = <Type, Action<Intent>>{
      _AdjustSliderIntent: CallbackAction<_AdjustSliderIntent>(
        onInvoke: _actionHandler,
      ),
    };
529 530 531 532
  }

  @override
  void dispose() {
533
    interactionTimer?.cancel();
534 535
    overlayController.dispose();
    valueIndicatorController.dispose();
536 537
    enableController.dispose();
    positionController.dispose();
538
    if (overlayEntry != null) {
539
      overlayEntry!.remove();
540 541
      overlayEntry = null;
    }
542
    super.dispose();
543 544
  }

Hixie's avatar
Hixie committed
545
  void _handleChanged(double value) {
546
    assert(widget.onChanged != null);
547 548
    final double lerpValue = _lerp(value);
    if (lerpValue != widget.value) {
549
      widget.onChanged!(lerpValue);
550
    }
Hixie's avatar
Hixie committed
551 552
  }

553 554
  void _handleDragStart(double value) {
    assert(widget.onChangeStart != null);
555
    widget.onChangeStart!(_lerp(value));
556 557 558 559
  }

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

563
  void _actionHandler(_AdjustSliderIntent intent) {
564
    final _RenderSlider renderSlider = _renderObjectKey.currentContext!.findRenderObject()! as _RenderSlider;
565
    final TextDirection textDirection = Directionality.of(_renderObjectKey.currentContext!);
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 598 599 600 601 602 603 604 605 606 607 608 609
    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; });
    }
  }

610 611 612 613 614 615
  // 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;
616 617
  }

618 619 620 621
  // 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);
622
    return widget.max > widget.min ? (value - widget.min) / (widget.max - widget.min) : 0.0;
623
  }
624

625
  @override
626
  Widget build(BuildContext context) {
627
    assert(debugCheckHasMaterial(context));
628
    assert(debugCheckHasMediaQuery(context));
629

630 631 632 633 634
    switch (widget._sliderType) {
      case _SliderType.material:
        return _buildMaterialSlider(context);

      case _SliderType.adaptive: {
635
        final ThemeData theme = Theme.of(context);
636 637 638 639
        assert(theme.platform != null);
        switch (theme.platform) {
          case TargetPlatform.android:
          case TargetPlatform.fuchsia:
640 641
          case TargetPlatform.linux:
          case TargetPlatform.windows:
642 643
            return _buildMaterialSlider(context);
          case TargetPlatform.iOS:
644
          case TargetPlatform.macOS:
645 646 647 648 649 650 651
            return _buildCupertinoSlider(context);
        }
      }
    }
  }

  Widget _buildMaterialSlider(BuildContext context) {
652
    final ThemeData theme = Theme.of(context);
653 654 655 656
    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
657 658 659 660
    // 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.
661

662 663 664
    const double _defaultTrackHeight = 4;
    const SliderTrackShape _defaultTrackShape = RoundedRectSliderTrackShape();
    const SliderTickMarkShape _defaultTickMarkShape = RoundSliderTickMarkShape();
665
    const SliderComponentShape _defaultOverlayShape = RoundSliderOverlayShape();
666 667
    const SliderComponentShape _defaultThumbShape = RoundSliderThumbShape();
    const SliderComponentShape _defaultValueIndicatorShape = RectangularSliderValueIndicatorShape();
668 669 670 671 672 673 674
    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;
675
    final Color valueIndicatorColor;
676 677 678 679 680 681
    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;
    }

682 683 684 685 686 687 688 689 690 691
    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),
692
      thumbColor: widget.thumbColor ?? widget.activeColor ?? sliderTheme.thumbColor ?? theme.colorScheme.primary,
693
      disabledThumbColor: sliderTheme.disabledThumbColor ?? Color.alphaBlend(theme.colorScheme.onSurface.withOpacity(.38), theme.colorScheme.surface),
694
      overlayColor: widget.activeColor?.withOpacity(0.12) ?? sliderTheme.overlayColor ?? theme.colorScheme.primary.withOpacity(0.12),
695
      valueIndicatorColor: valueIndicatorColor,
696 697 698 699
      trackShape: sliderTheme.trackShape ?? _defaultTrackShape,
      tickMarkShape: sliderTheme.tickMarkShape ?? _defaultTickMarkShape,
      thumbShape: sliderTheme.thumbShape ?? _defaultThumbShape,
      overlayShape: sliderTheme.overlayShape ?? _defaultOverlayShape,
700
      valueIndicatorShape: valueIndicatorShape,
701
      showValueIndicator: sliderTheme.showValueIndicator ?? _defaultShowValueIndicator,
702
      valueIndicatorTextStyle: sliderTheme.valueIndicatorTextStyle ?? theme.textTheme.bodyText1!.copyWith(
703 704 705
        color: theme.colorScheme.onPrimary,
      ),
    );
706 707 708 709 710 711 712 713
    final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs<MouseCursor>(
      widget.mouseCursor ?? MaterialStateMouseCursor.clickable,
      <MaterialState>{
        if (!_enabled) MaterialState.disabled,
        if (_hovering) MaterialState.hovered,
        if (_focused) MaterialState.focused,
      },
    );
714

715 716 717
    // 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.
718
    Size _screenSize() => MediaQuery.of(context).size;
719

720 721
    return Semantics(
      container: true,
722
      slider: true,
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
      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,
740
            textScaleFactor: MediaQuery.of(context).textScaleFactor,
741 742 743 744 745 746 747 748 749
            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,
          ),
750
        ),
751
      ),
752 753
    );
  }
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769

  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,
770
        thumbColor: widget.thumbColor ?? CupertinoColors.white,
771 772 773
      ),
    );
  }
774 775
  final LayerLink _layerLink = LayerLink();

776
  OverlayEntry? overlayEntry;
777 778 779 780 781 782 783 784 785 786 787 788 789

  void showValueIndicator() {
    if (overlayEntry == null) {
      overlayEntry = OverlayEntry(
        builder: (BuildContext context) {
          return CompositedTransformFollower(
            link: _layerLink,
            child: _ValueIndicatorRenderObjectWidget(
              state: this,
            ),
          );
        },
      );
790
      Overlay.of(context)!.insert(overlayEntry!);
791 792
    }
  }
793 794
}

795

796
class _SliderRenderObjectWidget extends LeafRenderObjectWidget {
797
  const _SliderRenderObjectWidget({
798 799 800 801 802 803 804 805 806 807 808 809 810 811
    Key? key,
    required this.value,
    required this.divisions,
    required this.label,
    required this.sliderTheme,
    required this.textScaleFactor,
    required this.screenSize,
    required this.onChanged,
    required this.onChangeStart,
    required this.onChangeEnd,
    required this.state,
    required this.semanticFormatterCallback,
    required this.hasFocus,
    required this.hovering,
812
  }) : super(key: key);
813 814

  final double value;
815 816
  final int? divisions;
  final String? label;
817
  final SliderThemeData sliderTheme;
818 819
  final double textScaleFactor;
  final Size screenSize;
820 821 822 823
  final ValueChanged<double>? onChanged;
  final ValueChanged<double>? onChangeStart;
  final ValueChanged<double>? onChangeEnd;
  final SemanticFormatterCallback? semanticFormatterCallback;
824
  final _SliderState state;
825 826
  final bool hasFocus;
  final bool hovering;
827

828
  @override
829
  _RenderSlider createRenderObject(BuildContext context) {
830
    return _RenderSlider(
831 832 833
      value: value,
      divisions: divisions,
      label: label,
834
      sliderTheme: sliderTheme,
835 836
      textScaleFactor: textScaleFactor,
      screenSize: screenSize,
837
      onChanged: onChanged,
838 839
      onChangeStart: onChangeStart,
      onChangeEnd: onChangeEnd,
840
      state: state,
841
      textDirection: Directionality.of(context),
842
      semanticFormatterCallback: semanticFormatterCallback,
843
      platform: Theme.of(context).platform,
844 845
      hasFocus: hasFocus,
      hovering: hovering,
846 847
    );
  }
848

849
  @override
850
  void updateRenderObject(BuildContext context, _RenderSlider renderObject) {
851
    renderObject
852 853
      // We should update the `divisions` ahead of `value`, because the `value`
      // setter dependent on the `divisions`.
854
      ..divisions = divisions
855
      ..value = value
856
      ..label = label
857
      ..sliderTheme = sliderTheme
858 859
      ..textScaleFactor = textScaleFactor
      ..screenSize = screenSize
860
      ..onChanged = onChanged
861 862
      ..onChangeStart = onChangeStart
      ..onChangeEnd = onChangeEnd
863
      ..textDirection = Directionality.of(context)
864
      ..semanticFormatterCallback = semanticFormatterCallback
865
      ..platform = Theme.of(context).platform
866 867
      ..hasFocus = hasFocus
      ..hovering = hovering;
868 869
    // Ticker provider cannot change since there's a 1:1 relationship between
    // the _SliderRenderObjectWidget object and the _SliderState object.
870 871 872
  }
}

873
class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
874
  _RenderSlider({
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
    required double value,
    required int? divisions,
    required String? label,
    required SliderThemeData sliderTheme,
    required double textScaleFactor,
    required Size screenSize,
    required TargetPlatform platform,
    required ValueChanged<double>? onChanged,
    required SemanticFormatterCallback? semanticFormatterCallback,
    required this.onChangeStart,
    required this.onChangeEnd,
    required _SliderState state,
    required TextDirection textDirection,
    required bool hasFocus,
    required bool hovering,
890
  }) : assert(value != null && value >= 0.0 && value <= 1.0),
891 892 893 894 895 896 897 898 899 900 901 902 903
        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,
904
        _hasFocus = hasFocus,
905
        _hovering = hovering {
Ian Hickson's avatar
Ian Hickson committed
906
    _updateLabelPainter();
907 908
    final GestureArenaTeam team = GestureArenaTeam();
    _drag = HorizontalDragGestureRecognizer()
909
      ..team = team
910 911
      ..onStart = _handleDragStart
      ..onUpdate = _handleDragUpdate
912 913
      ..onEnd = _handleDragEnd
      ..onCancel = _endInteraction;
914
    _tap = TapGestureRecognizer()
915
      ..team = team
916
      ..onTapDown = _handleTapDown
917
      ..onTapUp = _handleTapUp;
918
    _overlayAnimation = CurvedAnimation(
919 920 921
      parent: _state.overlayController,
      curve: Curves.fastOutSlowIn,
    );
922
    _valueIndicatorAnimation = CurvedAnimation(
923
      parent: _state.valueIndicatorController,
924
      curve: Curves.fastOutSlowIn,
925 926
    )..addStatusListener((AnimationStatus status) {
      if (status == AnimationStatus.dismissed && _state.overlayEntry != null) {
927
        _state.overlayEntry!.remove();
928 929 930
        _state.overlayEntry = null;
      }
    });
931
    _enableAnimation = CurvedAnimation(
932 933 934
      parent: _state.enableController,
      curve: Curves.easeInOut,
    );
935
  }
936 937
  static const Duration _positionAnimationDuration = Duration(milliseconds: 75);
  static const Duration _minimumInteractionTime = Duration(milliseconds: 500);
938 939 940 941 942 943 944 945

  // 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);
946
  double get _maxSliderPartHeight => _sliderPartSizes.map((Size size) => size.height).reduce(math.max);
947
  List<Size> get _sliderPartSizes => <Size>[
948 949 950
    _sliderTheme.overlayShape!.getPreferredSize(isInteractive, isDiscrete),
    _sliderTheme.thumbShape!.getPreferredSize(isInteractive, isDiscrete),
    _sliderTheme.tickMarkShape!.getPreferredSize(isEnabled: isInteractive, sliderTheme: sliderTheme),
951
  ];
952
  double get _minPreferredTrackHeight => _sliderTheme.trackHeight!;
953

954
  final _SliderState _state;
955 956 957
  late Animation<double> _overlayAnimation;
  late Animation<double> _valueIndicatorAnimation;
  late Animation<double> _enableAnimation;
958
  final TextPainter _labelPainter = TextPainter();
959 960
  late HorizontalDragGestureRecognizer _drag;
  late TapGestureRecognizer _tap;
961 962 963
  bool _active = false;
  double _currentDragValue = 0.0;

964 965 966
  // 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).
967
  Rect get _trackRect => _sliderTheme.trackShape!.getPreferredRect(
968 969 970 971 972
    parentBox: this,
    offset: Offset.zero,
    sliderTheme: _sliderTheme,
    isDiscrete: false,
  );
973 974 975

  bool get isInteractive => onChanged != null;

976
  bool get isDiscrete => divisions != null && divisions! > 0;
977

978 979
  double get value => _value;
  double _value;
980
  set value(double newValue) {
981
    assert(newValue != null && newValue >= 0.0 && newValue <= 1.0);
982 983
    final double convertedValue = isDiscrete ? _discretize(newValue) : newValue;
    if (convertedValue == _value) {
984
      return;
985 986 987
    }
    _value = convertedValue;
    if (isDiscrete) {
988 989 990 991 992 993 994
      // 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)
995
        : Duration.zero;
996 997 998 999
      _state.positionController.animateTo(convertedValue, curve: Curves.easeInOut);
    } else {
      _state.positionController.value = convertedValue;
    }
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    markNeedsSemanticsUpdate();
  }

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

1012 1013 1014
  SemanticFormatterCallback? _semanticFormatterCallback;
  SemanticFormatterCallback? get semanticFormatterCallback => _semanticFormatterCallback;
  set semanticFormatterCallback(SemanticFormatterCallback? value) {
1015 1016 1017 1018
    if (_semanticFormatterCallback == value)
      return;
    _semanticFormatterCallback = value;
    markNeedsSemanticsUpdate();
1019 1020
  }

1021 1022 1023
  int? get divisions => _divisions;
  int? _divisions;
  set divisions(int? value) {
1024
    if (value == _divisions) {
1025
      return;
1026
    }
1027
    _divisions = value;
1028 1029 1030
    markNeedsPaint();
  }

1031 1032 1033
  String? get label => _label;
  String? _label;
  set label(String? value) {
1034
    if (value == _label) {
1035
      return;
1036
    }
1037
    _label = value;
Ian Hickson's avatar
Ian Hickson committed
1038
    _updateLabelPainter();
1039 1040
  }

1041 1042 1043 1044
  SliderThemeData get sliderTheme => _sliderTheme;
  SliderThemeData _sliderTheme;
  set sliderTheme(SliderThemeData value) {
    if (value == _sliderTheme) {
1045
      return;
1046 1047
    }
    _sliderTheme = value;
1048 1049 1050
    markNeedsPaint();
  }

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

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

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

1090 1091
  ValueChanged<double>? onChangeStart;
  ValueChanged<double>? onChangeEnd;
1092

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

1104 1105 1106 1107 1108 1109 1110 1111 1112
  /// 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);
1113
    markNeedsSemanticsUpdate();
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
  }

  /// 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();
      }
    }
  }
1140

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

1154 1155 1156
  double get _adjustmentUnit {
    switch (_platform) {
      case TargetPlatform.iOS:
1157
      case TargetPlatform.macOS:
1158
        // Matches iOS implementation of material slider.
1159 1160 1161
        return 0.1;
      case TargetPlatform.android:
      case TargetPlatform.fuchsia:
1162 1163 1164
      case TargetPlatform.linux:
      case TargetPlatform.windows:
        // Matches Android implementation of material slider.
1165 1166 1167 1168
        return 0.05;
    }
  }

Ian Hickson's avatar
Ian Hickson committed
1169 1170 1171
  void _updateLabelPainter() {
    if (label != null) {
      _labelPainter
1172
        ..text = TextSpan(
1173 1174 1175
          style: _sliderTheme.valueIndicatorTextStyle,
          text: label,
        )
Ian Hickson's avatar
Ian Hickson committed
1176
        ..textDirection = textDirection
1177
        ..textScaleFactor = textScaleFactor
Ian Hickson's avatar
Ian Hickson committed
1178 1179 1180 1181 1182 1183 1184 1185
        ..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();
1186 1187
  }

1188 1189 1190 1191 1192 1193 1194
  @override
  void systemFontsDidChange() {
    super.systemFontsDidChange();
    _labelPainter.markNeedsLayout();
    _updateLabelPainter();
  }

1195 1196 1197
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
1198 1199
    _overlayAnimation.addListener(markNeedsPaint);
    _valueIndicatorAnimation.addListener(markNeedsPaint);
1200 1201 1202 1203 1204 1205
    _enableAnimation.addListener(markNeedsPaint);
    _state.positionController.addListener(markNeedsPaint);
  }

  @override
  void detach() {
1206 1207
    _overlayAnimation.removeListener(markNeedsPaint);
    _valueIndicatorAnimation.removeListener(markNeedsPaint);
1208 1209 1210 1211 1212
    _enableAnimation.removeListener(markNeedsPaint);
    _state.positionController.removeListener(markNeedsPaint);
    super.detach();
  }

1213 1214 1215 1216 1217 1218 1219 1220 1221
  double _getValueFromVisualPosition(double visualPosition) {
    switch (textDirection) {
      case TextDirection.rtl:
        return 1.0 - visualPosition;
      case TextDirection.ltr:
        return visualPosition;
    }
  }

1222
  double _getValueFromGlobalPosition(Offset globalPosition) {
1223
    final double visualPosition = (globalToLocal(globalPosition).dx - _trackRect.left) / _trackRect.width;
1224
    return _getValueFromVisualPosition(visualPosition);
1225 1226
  }

1227
  double _discretize(double value) {
1228
    double result = value.clamp(0.0, 1.0);
1229
    if (isDiscrete) {
1230
      result = (result * divisions!).round() / divisions!;
1231
    }
1232 1233
    return result;
  }
1234

1235
  void _startInteraction(Offset globalPosition) {
1236
    _state.showValueIndicator();
1237
    if (!_active && isInteractive) {
1238
      _active = true;
1239 1240 1241
      // 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.
1242
      onChangeStart?.call(_discretize(value));
1243
      _currentDragValue = _getValueFromGlobalPosition(globalPosition);
1244
      onChanged!(_discretize(_currentDragValue));
1245 1246 1247
      _state.overlayController.forward();
      if (showValueIndicator) {
        _state.valueIndicatorController.forward();
1248
        _state.interactionTimer?.cancel();
1249
        _state.interactionTimer = Timer(_minimumInteractionTime * timeDilation, () {
1250 1251 1252
          _state.interactionTimer = null;
          if (!_active &&
              _state.valueIndicatorController.status == AnimationStatus.completed) {
1253 1254 1255 1256
            _state.valueIndicatorController.reverse();
          }
        });
      }
1257 1258 1259 1260
    }
  }

  void _endInteraction() {
1261 1262 1263 1264
    if (!_state.mounted) {
      return;
    }

1265
    if (_active && _state.mounted) {
1266
      onChangeEnd?.call(_discretize(_currentDragValue));
1267 1268
      _active = false;
      _currentDragValue = 0.0;
1269
      _state.overlayController.reverse();
1270

1271
      if (showValueIndicator && _state.interactionTimer == null) {
1272 1273
        _state.valueIndicatorController.reverse();
      }
1274 1275 1276
    }
  }

1277 1278 1279
  void _handleDragStart(DragStartDetails details) {
    _startInteraction(details.globalPosition);
  }
1280

1281
  void _handleDragUpdate(DragUpdateDetails details) {
1282 1283 1284 1285
    if (!_state.mounted) {
      return;
    }

1286
    if (isInteractive) {
1287
      final double valueDelta = details.primaryDelta! / _trackRect.width;
1288 1289 1290 1291 1292 1293 1294 1295
      switch (textDirection) {
        case TextDirection.rtl:
          _currentDragValue -= valueDelta;
          break;
        case TextDirection.ltr:
          _currentDragValue += valueDelta;
          break;
      }
1296
      onChanged!(_discretize(_currentDragValue));
1297 1298 1299
    }
  }

1300 1301 1302
  void _handleDragEnd(DragEndDetails details) {
    _endInteraction();
  }
1303

1304 1305 1306
  void _handleTapDown(TapDownDetails details) {
    _startInteraction(details.globalPosition);
  }
1307

1308 1309 1310
  void _handleTapUp(TapUpDetails details) {
    _endInteraction();
  }
1311

1312
  @override
1313
  bool hitTestSelf(Offset position) => true;
1314

1315
  @override
Ian Hickson's avatar
Ian Hickson committed
1316
  void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
1317
    assert(debugHandleEvent(event, entry));
1318 1319
    if (event is PointerDownEvent && isInteractive) {
      // We need to add the drag first so that it has priority.
1320
      _drag.addPointer(event);
1321 1322
      _tap.addPointer(event);
    }
1323 1324
  }

1325
  @override
1326
  double computeMinIntrinsicWidth(double height) => _minPreferredTrackWidth + _maxSliderPartWidth;
1327 1328

  @override
1329
  double computeMaxIntrinsicWidth(double height) => _minPreferredTrackWidth + _maxSliderPartWidth;
1330 1331

  @override
1332
  double computeMinIntrinsicHeight(double width) => math.max(_minPreferredTrackHeight, _maxSliderPartHeight);
1333 1334

  @override
1335
  double computeMaxIntrinsicHeight(double width) => math.max(_minPreferredTrackHeight, _maxSliderPartHeight);
1336 1337 1338 1339 1340

  @override
  bool get sizedByParent => true;

  @override
1341 1342
  Size computeDryLayout(BoxConstraints constraints) {
    return Size(
1343
      constraints.hasBoundedWidth ? constraints.maxWidth : _minPreferredTrackWidth + _maxSliderPartWidth,
1344
      constraints.hasBoundedHeight ? constraints.maxHeight : math.max(_minPreferredTrackHeight, _maxSliderPartHeight),
1345 1346 1347
    );
  }

1348
  @override
1349
  void paint(PaintingContext context, Offset offset) {
1350
    final double value = _state.positionController.value;
1351

1352 1353 1354
    // 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.
1355
    final double visualPosition;
1356 1357 1358 1359 1360 1361 1362 1363
    switch (textDirection) {
      case TextDirection.rtl:
        visualPosition = 1.0 - value;
        break;
      case TextDirection.ltr:
        visualPosition = value;
        break;
    }
1364

1365
    final Rect trackRect = _sliderTheme.trackShape!.getPreferredRect(
1366 1367 1368
      parentBox: this,
      offset: offset,
      sliderTheme: _sliderTheme,
1369
      isDiscrete: isDiscrete,
1370
    );
1371
    final Offset thumbCenter = Offset(trackRect.left + visualPosition * trackRect.width, trackRect.center.dy);
1372

1373
    _sliderTheme.trackShape!.paint(
1374 1375 1376 1377 1378 1379 1380 1381
      context,
      offset,
      parentBox: this,
      sliderTheme: _sliderTheme,
      enableAnimation: _enableAnimation,
      textDirection: _textDirection,
      thumbCenter: thumbCenter,
      isDiscrete: isDiscrete,
1382
      isEnabled: isInteractive,
1383 1384
    );

1385
    if (!_overlayAnimation.isDismissed) {
1386
      _sliderTheme.overlayShape!.paint(
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
        context,
        thumbCenter,
        activationAnimation: _overlayAnimation,
        enableAnimation: _enableAnimation,
        isDiscrete: isDiscrete,
        labelPainter: _labelPainter,
        parentBox: this,
        sliderTheme: _sliderTheme,
        textDirection: _textDirection,
        value: _value,
1397 1398
        textScaleFactor: _textScaleFactor,
        sizeWithOverflow: screenSize.isEmpty ? size : screenSize,
1399 1400 1401 1402
      );
    }

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

    if (isInteractive && label != null && !_valueIndicatorAnimation.isDismissed) {
1433
      if (showValueIndicator) {
1434
        _state.paintValueIndicator = (PaintingContext context, Offset offset) {
1435
          if (attached) {
1436
            _sliderTheme.valueIndicatorShape!.paint(
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
              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,
            );
          }
1451
        };
1452
      }
1453
    }
Adam Barth's avatar
Adam Barth committed
1454

1455
    _sliderTheme.thumbShape!.paint(
1456 1457
      context,
      thumbCenter,
1458
      activationAnimation: _overlayAnimation,
1459 1460 1461 1462 1463 1464 1465
      enableAnimation: _enableAnimation,
      isDiscrete: isDiscrete,
      labelPainter: _labelPainter,
      parentBox: this,
      sliderTheme: _sliderTheme,
      textDirection: _textDirection,
      value: _value,
1466 1467
      textScaleFactor: textScaleFactor,
      sizeWithOverflow: screenSize.isEmpty ? size : screenSize,
1468
    );
1469
  }
1470 1471

  @override
1472 1473
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
1474

1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
    // 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;
1488
    if (isInteractive) {
1489 1490
      config.onIncrease = increaseAction;
      config.onDecrease = decreaseAction;
1491 1492 1493
    }
    config.label = _label ?? '';
    if (semanticFormatterCallback != null) {
1494 1495 1496
      config.value = semanticFormatterCallback!(_state._lerp(value));
      config.increasedValue = semanticFormatterCallback!(_state._lerp((value + _semanticActionUnit).clamp(0.0, 1.0)));
      config.decreasedValue = semanticFormatterCallback!(_state._lerp((value - _semanticActionUnit).clamp(0.0, 1.0)));
1497 1498 1499 1500
    } 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()}%';
1501 1502 1503
    }
  }

1504
  double get _semanticActionUnit => divisions != null ? 1.0 / divisions! : _adjustmentUnit;
1505

1506
  void increaseAction() {
1507
    if (isInteractive) {
1508
      onChanged!((value + _semanticActionUnit).clamp(0.0, 1.0));
1509
    }
1510 1511
  }

1512
  void decreaseAction() {
1513
    if (isInteractive) {
1514
      onChanged!((value - _semanticActionUnit).clamp(0.0, 1.0));
1515
    }
1516
  }
1517
}
1518

1519 1520
class _AdjustSliderIntent extends Intent {
  const _AdjustSliderIntent({
1521
    required this.type,
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
  });

  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,
}

1542 1543
class _ValueIndicatorRenderObjectWidget extends LeafRenderObjectWidget {
  const _ValueIndicatorRenderObjectWidget({
1544
    required this.state,
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
  });

  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({
1563
    required _SliderState state,
1564 1565 1566 1567 1568 1569
  }) : _state = state {
    _valueIndicatorAnimation = CurvedAnimation(
      parent: _state.valueIndicatorController,
      curve: Curves.fastOutSlowIn,
    );
  }
1570
  late Animation<double> _valueIndicatorAnimation;
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
  _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) {
1592
    _state.paintValueIndicator?.call(context, offset);
1593
  }
1594 1595 1596 1597 1598

  @override
  Size computeDryLayout(BoxConstraints constraints) {
    return constraints.smallest;
  }
1599
}