Repository navigation
Expand file tree
/
Copy pathrange_slider.dart
More file actions
2431 lines (2192 loc) · 85.8 KB
/
Copy pathrange_slider.dart
File metadata and controls
2431 lines (2192 loc) · 85.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
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
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'app.dart';
/// @docImport 'checkbox.dart';
/// @docImport 'color_scheme.dart';
/// @docImport 'material.dart';
/// @docImport 'radio.dart';
/// @docImport 'scaffold.dart';
/// @docImport 'slider.dart';
/// @docImport 'switch.dart';
/// @docImport 'text_theme.dart';
library;
import 'dart:async';
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart' show timeDilation;
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'color_scheme.dart';
import 'constants.dart';
import 'debug.dart';
import 'range_slider_parts.dart';
import 'slider_theme.dart';
import 'slider_value_indicator_shape.dart';
import 'theme.dart';
part 'generated/range_slider_defaults_m3.g.dart';
// Examples can assume:
// RangeValues _rangeValues = const RangeValues(0.3, 0.7);
// RangeValues _dollarsRange = const RangeValues(50, 100);
// void setState(VoidCallback fn) { }
/// [RangeSlider] 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 PaintRangeValueIndicator = void Function(PaintingContext context, Offset offset);
/// A Material Design range slider.
///
/// Used to select a range from a range of values.
///
/// Learn more about [RangeSlider] on the [Flutter YouTube channel](https://www.youtube.com/watch?v=ufb4gIPDmEs).
///
/// <callout-box>
///
/// 
///
/// This range values are in intervals of 20 because the Range Slider has 5
/// divisions, from 0 to 100. This means are values are split between 0, 20, 40,
/// 60, 80, and 100. The range values are initialized with 40 and 80 in this demo.
///
// TODO(framework): Replace the following block with a @dartpad directive
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
/// {@macro material_ui.dartpad_guide}
///
/// {@example /example/lib/range_slider/range_slider.0.dart#body}
///
/// </callout-box>
///
/// A range slider can be used to select from either a continuous or a discrete
/// set of 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
/// indicates the number of discrete intervals. For example, if [min] is 0.0 and
/// [max] is 50.0 and [divisions] is 5, then the slider can take on the
/// discrete values 0.0, 10.0, 20.0, 30.0, 40.0, and 50.0.
///
/// The terms for the parts of a slider are:
///
/// * The "thumbs", which are the shapes that slide horizontally when the user
/// drags them to change the selected range.
/// * The "track", which is the horizontal line that the thumbs can be dragged
/// along.
/// * The "tick marks", which mark the discrete values of a discrete slider.
/// * The "overlay", which is a highlight that's drawn over a thumb in response
/// to a user tap-down gesture.
/// * The "value indicators", which are the shapes that pop up when the user
/// is dragging a thumb to show the value being selected.
/// * The "active" segment of the slider is the segment between the two thumbs.
/// * The "inactive" slider segments are the two track intervals outside of the
/// slider's thumbs.
///
/// The range 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]).
///
/// The range 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 range slider will listen for the [onChanged] callback
/// and rebuild the slider with new [values] to update the visual appearance of
/// the slider. To know when the value starts to change, or when it is done
/// changing, set the optional callbacks [onChangeStart] and/or [onChangeEnd].
///
/// By default, a slider will be as wide as possible, centered vertically. When
/// given unbounded constraints, it will attempt to make the track 144 pixels
/// wide (including margins on each side) and will shrink-wrap vertically.
///
/// Requires one of its ancestors to be a [Material] widget. This is typically
/// provided by a [Scaffold] widget.
///
/// Requires one of its ancestors to be a [MediaQuery] widget. Typically, a
/// [MediaQuery] widget is introduced by the [MaterialApp] or [WidgetsApp]
/// widget at the top of your application widget tree.
///
/// 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] inside 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 colors, and other visual properties is achieved using a
/// [SliderThemeData].
///
/// See also:
///
/// * [SliderTheme] and [SliderThemeData] for information about controlling
/// the visual appearance of the slider.
/// * [Slider], for a single-valued slider.
/// * [Radio], for selecting among a set of explicit values.
/// * [Checkbox] and [Switch], for toggling a particular value on or off.
/// * <https://material.io/design/components/sliders.html>
/// * [MediaQuery], from which the text scale factor is obtained.
class RangeSlider extends StatefulWidget {
/// Creates a Material Design range slider.
///
/// The range 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 range slider will listen for the
/// [onChanged] callback and rebuild the slider with new [values] to update
/// the visual appearance of the slider. To know when the value starts to
/// change, or when it is done changing, set the optional callbacks
/// [onChangeStart] and/or [onChangeEnd].
///
/// * [values], which determines currently selected values for this range
/// slider.
/// * [onChanged], which is called while the user is selecting a new value for
/// the range slider.
/// * [onChangeStart], which is called when the user starts to select a new
/// value for the range slider.
/// * [onChangeEnd], which is called when the user is done selecting a new
/// value for the range slider.
///
/// 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].
///
/// The [min] must be less than or equal to the [max].
///
/// The [RangeValues.start] attribute of the [values] parameter must be less
/// than or equal to its [RangeValues.end] attribute. The [RangeValues.start]
/// and [RangeValues.end] attributes of the [values] parameter must be greater
/// than or equal to the [min] parameter and less than or equal to the [max]
/// parameter.
///
/// The [divisions] parameter must be null or greater than zero.
RangeSlider({
super.key,
required this.values,
required this.onChanged,
this.onChangeStart,
this.onChangeEnd,
this.min = 0.0,
this.max = 1.0,
this.divisions,
this.labels,
this.activeColor,
this.inactiveColor,
this.overlayColor,
this.mouseCursor,
this.semanticFormatterCallback,
this.padding,
@Deprecated(
'Set this flag to false to opt into the 2024 range slider appearance. Defaults to true. '
'In the future, this flag will default to false. Use SliderThemeData to customize individual properties. '
'This feature was deprecated after v3.30.0-0.1.pre.',
)
this.year2023,
}) : assert(min <= max),
assert(values.start <= values.end),
assert(values.start >= min && values.start <= max),
assert(values.end >= min && values.end <= max),
assert(divisions == null || divisions > 0);
/// The currently selected values for this range slider.
///
/// The slider's thumbs are drawn at horizontal positions that corresponds to
/// these values.
final RangeValues values;
/// Called when the user is selecting a new value for the slider by dragging.
///
/// The slider passes the new values to the callback but does not actually
/// change state until the parent widget rebuilds the slider with the new
/// values.
///
/// If null, the slider will be displayed as disabled.
///
/// 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:
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
/// ```dart
/// RangeSlider(
/// values: _rangeValues,
/// min: 1.0,
/// max: 10.0,
/// onChanged: (RangeValues newValues) {
/// setState(() {
/// _rangeValues = newValues;
/// });
/// },
/// )
/// ```
///
/// </callout-box>
///
/// See also:
///
/// * [onChangeStart], which is called when the user starts changing the
/// values.
/// * [onChangeEnd], which is called when the user stops changing the values.
final ValueChanged<RangeValues>? onChanged;
/// Called when the user starts selecting new values for the slider.
///
/// This callback shouldn't be used to update the slider [values] (use
/// [onChanged] for that). Rather, it should be used to be notified when the
/// user has started selecting a new value by starting a drag or with a tap.
///
/// The values passed will be the last [values] that the slider had before the
/// change began.
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
/// ```dart
/// RangeSlider(
/// values: _rangeValues,
/// min: 1.0,
/// max: 10.0,
/// onChanged: (RangeValues newValues) {
/// setState(() {
/// _rangeValues = newValues;
/// });
/// },
/// onChangeStart: (RangeValues startValues) {
/// print('Started change at $startValues');
/// },
/// )
/// ```
///
/// </callout-box>
///
/// See also:
///
/// * [onChangeEnd] for a callback that is called when the value change is
/// complete.
final ValueChanged<RangeValues>? onChangeStart;
/// Called when the user is done selecting new values for the slider.
///
/// This differs from [onChanged] because it is only called once at the end
/// of the interaction, while [onChanged] is called as the value is getting
/// updated within the interaction.
///
/// This callback shouldn't be used to update the slider [values] (use
/// [onChanged] for that). Rather, it should be used to know when the user has
/// completed selecting a new [values] by ending a drag or a click.
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
/// ```dart
/// RangeSlider(
/// values: _rangeValues,
/// min: 1.0,
/// max: 10.0,
/// onChanged: (RangeValues newValues) {
/// setState(() {
/// _rangeValues = newValues;
/// });
/// },
/// onChangeEnd: (RangeValues endValues) {
/// print('Ended change at $endValues');
/// },
/// )
/// ```
///
/// </callout-box>
///
/// See also:
///
/// * [onChangeStart] for a callback that is called when a value change
/// begins.
final ValueChanged<RangeValues>? onChangeEnd;
/// The minimum value the user can select.
///
/// 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.
final double min;
/// The maximum value the user can select.
///
/// 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.
final double max;
/// The number of discrete divisions.
///
/// Typically used with [labels] to show the current discrete values.
///
/// If null, the slider is continuous.
final int? divisions;
/// Labels to show as text in the [SliderThemeData.rangeValueIndicatorShape]
/// when the slider is active and [SliderThemeData.showValueIndicator]
/// is satisfied.
///
/// There are two labels: one for the start thumb and one for the end thumb.
///
/// Each label is rendered using the active [ThemeData]'s
/// [TextTheme.bodyLarge] text style, with the theme data's
/// [ColorScheme.onPrimary] color. The label's text style can be overridden
/// with [SliderThemeData.valueIndicatorTextStyle].
///
/// If null, then the value indicator will not be displayed.
///
/// See also:
///
/// * [RangeSliderValueIndicatorShape] for how to create a custom value
/// indicator shape.
final RangeLabels? labels;
/// The color of the track's active segment, i.e. the span of track between
/// the thumbs.
///
/// Defaults to [ColorScheme.primary].
///
/// Using a [SliderTheme] gives more fine-grained control over the
/// appearance of various components of the slider.
final Color? activeColor;
/// The color of the track's inactive segments, i.e. the span of tracks
/// between the min and the start thumb, and the end thumb and the max.
///
/// If null, [SliderThemeData.inactiveTrackColor] of the ambient [SliderTheme]
/// is used. If [RangeSlider.year2023] is false and [ThemeData.useMaterial3] is true,
/// then [ColorScheme.secondaryContainer] is used. Otherwise, [ColorScheme.primary]
/// with an opacity of 0.24 is used.
///
/// Using a [SliderTheme] gives more fine-grained control over the
/// appearance of various components of the slider.
final Color? inactiveColor;
/// The highlight color that's typically used to indicate that
/// the range slider thumb is hovered or dragged.
///
/// If this property is null, [RangeSlider] will use [activeColor] with
/// an opacity of 0.12. If null, [SliderThemeData.overlayColor]
/// will be used, otherwise defaults to [ColorScheme.primary] with
/// an opacity of 0.12.
final WidgetStateProperty<Color?>? overlayColor;
/// The cursor for a mouse pointer when it enters or is hovering over the
/// widget.
///
/// If null, then the value of [SliderThemeData.mouseCursor] is used. If that
/// is also null, then [WidgetStateMouseCursor.clickable] is used.
///
/// See also:
///
/// * [WidgetStateMouseCursor], which can be used to create a [MouseCursor].
final WidgetStateProperty<MouseCursor?>? mouseCursor;
/// The callback used to create a semantic value from the slider's values.
///
/// 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.
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
/// In the example below, a slider for currency values is configured to
/// announce a value with a currency label.
///
/// ```dart
/// RangeSlider(
/// values: _dollarsRange,
/// min: 20.0,
/// max: 330.0,
/// onChanged: (RangeValues newValues) {
/// setState(() {
/// _dollarsRange = newValues;
/// });
/// },
/// semanticFormatterCallback: (double newValue) {
/// return '${newValue.round()} dollars';
/// }
/// )
/// ```
///
/// </callout-box>
final SemanticFormatterCallback? semanticFormatterCallback;
/// Determines the padding around the [RangeSlider].
///
/// If specified, this padding overrides the vertical padding and the
/// horizontal padding of the [RangeSlider]. By default, the vertical padding
/// is the height of the overlay shape, and the horizontal padding is the
/// larger size between the width of the thumb shape and overlay shape.
final EdgeInsetsGeometry? padding;
/// When true, the [RangeSlider] will use the 2023 Material Design 3 appearance.
/// Defaults to true.
///
/// If this is set to false, the [RangeSlider] will use the latest Material Design 3
/// appearance, which was introduced in December 2023.
///
/// If [ThemeData.useMaterial3] is false, then this property is ignored.
@Deprecated(
'Set this flag to false to opt into the 2024 range slider appearance. Defaults to true. '
'In the future, this flag will default to false. Use SliderThemeData to customize individual properties. '
'This feature was deprecated after v3.30.0-0.1.pre.',
)
final bool? year2023;
// Touch width for the tap boundary of the slider thumbs.
static const double _minTouchTargetWidth = kMinInteractiveDimension;
@override
State<RangeSlider> createState() => _RangeSliderState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DoubleProperty('valueStart', values.start));
properties.add(DoubleProperty('valueEnd', values.end));
properties.add(
ObjectFlagProperty<ValueChanged<RangeValues>>('onChanged', onChanged, ifNull: 'disabled'),
);
properties.add(
ObjectFlagProperty<ValueChanged<RangeValues>>.has('onChangeStart', onChangeStart),
);
properties.add(ObjectFlagProperty<ValueChanged<RangeValues>>.has('onChangeEnd', onChangeEnd));
properties.add(DoubleProperty('min', min));
properties.add(DoubleProperty('max', max));
properties.add(IntProperty('divisions', divisions));
properties.add(StringProperty('labelStart', labels?.start));
properties.add(StringProperty('labelEnd', labels?.end));
properties.add(ColorProperty('activeColor', activeColor));
properties.add(ColorProperty('inactiveColor', inactiveColor));
properties.add(
ObjectFlagProperty<ValueChanged<double>>.has(
'semanticFormatterCallback',
semanticFormatterCallback,
),
);
}
}
class _RangeSliderState extends State<RangeSlider> with TickerProviderStateMixin {
static const Duration enableAnimationDuration = Duration(milliseconds: 75);
static const Duration valueIndicatorAnimationDuration = Duration(milliseconds: 100);
final FocusNode startFocusNode = FocusNode();
final FocusNode endFocusNode = FocusNode();
final GlobalKey _renderObjectKey = GlobalKey();
// Whether the slider is currently in the value adjustment mode while using
// directional navigation (e.g. a TV remote or D-pad). When false, arrow keys
// are left unhandled so they can move the focus between views; when true,
// arrow keys adjust the slider value. Toggled by the enter key. This has no
// effect when using traditional navigation.
bool _isEditingInDirectionalMode = false;
// The ambient navigation mode, cached so build() doesn't have to re-read the
// MediaQuery (and re-pick a shortcut map) on every pass.
NavigationMode _navigationMode = NavigationMode.traditional;
// Keyboard mapping for a focused range slider.
static const Map<ShortcutActivator, Intent> _traditionalNavShortcutMap =
<ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.arrowUp): _AdjustSliderIntent.up(),
SingleActivator(LogicalKeyboardKey.arrowDown): _AdjustSliderIntent.down(),
SingleActivator(LogicalKeyboardKey.arrowLeft): _AdjustSliderIntent.left(),
SingleActivator(LogicalKeyboardKey.arrowRight): _AdjustSliderIntent.right(),
};
// Keyboard mapping for a focused range slider when using directional
// navigation and not in the value adjustment mode. Only the enter key is
// handled, to enter the value adjustment mode. The arrow keys are left
// unhandled so they can move the focus between views.
static const Map<ShortcutActivator, Intent> _directionalNavShortcutMap =
<ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.enter): _ToggleRangeSliderEditModeIntent(),
};
// Keyboard mapping for a focused range slider when using directional
// navigation and in the value adjustment mode. The horizontal inputs adjust
// the value and the enter key exits the value adjustment mode. The vertical
// inputs are not handled to allow navigating out of the slider.
static const Map<ShortcutActivator, Intent> _directionalNavEditingShortcutMap =
<ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.arrowLeft): _AdjustSliderIntent.left(),
SingleActivator(LogicalKeyboardKey.arrowRight): _AdjustSliderIntent.right(),
SingleActivator(LogicalKeyboardKey.enter): _ToggleRangeSliderEditModeIntent(),
};
// Action mapping for the start thumb.
late Map<Type, Action<Intent>> _startActionMap;
// Action mapping for the end thumb.
late Map<Type, Action<Intent>> _endActionMap;
// Animation controller that is run when the overlay (a.k.a radial reaction)
// changes visibility in response to user interaction.
late AnimationController overlayController;
// Animation controller that is run when the value indicators change visibility.
late AnimationController valueIndicatorController;
// Animation controller that is run when enabling/disabling the slider.
late AnimationController enableController;
// Animation controllers that are run when transitioning between one value
// and the next on a discrete slider.
late AnimationController startPositionController;
late AnimationController endPositionController;
Timer? interactionTimer;
// Value Indicator paint Animation that appears on the Overlay.
PaintRangeValueIndicator? paintTopValueIndicator;
PaintRangeValueIndicator? paintBottomValueIndicator;
bool get _enabled => widget.onChanged != null;
bool _dragging = false;
bool _showStartFocusHighlight = false;
void _handleStartFocusHighlightChanged(bool showFocusHighlight) {
if (showFocusHighlight != _showStartFocusHighlight) {
setState(() {
_showStartFocusHighlight = showFocusHighlight;
});
}
}
bool _showEndFocusHighlight = false;
void _handleEndFocusHighlightChanged(bool showFocusHighlight) {
if (showFocusHighlight != _showEndFocusHighlight) {
setState(() {
_showEndFocusHighlight = showFocusHighlight;
});
}
}
bool _hovering = false;
bool _showHoverHighlight = false;
void _handleHoverChanged(bool hovering) {
if (hovering != _hovering) {
setState(() {
_hovering = hovering;
_showHoverHighlight = hovering && _enabled;
});
}
}
// Always keep the ValueIndicator visible on the Overlay; otherwise, it cannot be updated during the build phase.
final OverlayPortalController _valueIndicatorOverlayPortalController = OverlayPortalController(
debugLabel: 'RangeSlider ValueIndicator',
)..show();
@override
void initState() {
super.initState();
_startActionMap = <Type, Action<Intent>>{
_AdjustSliderIntent: CallbackAction<_AdjustSliderIntent>(
onInvoke: (_AdjustSliderIntent intent) => _actionHandler(intent, Thumb.start),
),
_ToggleRangeSliderEditModeIntent: CallbackAction<_ToggleRangeSliderEditModeIntent>(
onInvoke: (_ToggleRangeSliderEditModeIntent intent) => _toggleEditMode(),
),
};
_endActionMap = <Type, Action<Intent>>{
_AdjustSliderIntent: CallbackAction<_AdjustSliderIntent>(
onInvoke: (_AdjustSliderIntent intent) => _actionHandler(intent, Thumb.end),
),
_ToggleRangeSliderEditModeIntent: CallbackAction<_ToggleRangeSliderEditModeIntent>(
onInvoke: (_ToggleRangeSliderEditModeIntent intent) => _toggleEditMode(),
),
};
overlayController = AnimationController(duration: kRadialReactionDuration, vsync: this);
valueIndicatorController = AnimationController(
duration: valueIndicatorAnimationDuration,
vsync: this,
);
enableController = AnimationController(
duration: enableAnimationDuration,
vsync: this,
value: _enabled ? 1.0 : 0.0,
);
startPositionController = AnimationController(
duration: Duration.zero,
vsync: this,
value: _unlerp(widget.values.start),
);
endPositionController = AnimationController(
duration: Duration.zero,
vsync: this,
value: _unlerp(widget.values.end),
);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_navigationMode = MediaQuery.navigationModeOf(context);
}
@override
void didUpdateWidget(RangeSlider oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.onChanged == widget.onChanged) {
return;
}
final wasEnabled = oldWidget.onChanged != null;
final bool isEnabled = _enabled;
if (wasEnabled != isEnabled) {
if (isEnabled) {
enableController.forward();
} else {
enableController.reverse();
}
_showHoverHighlight = _hovering && isEnabled;
}
}
@override
void dispose() {
interactionTimer?.cancel();
overlayController.dispose();
valueIndicatorController.dispose();
enableController.dispose();
startPositionController.dispose();
endPositionController.dispose();
startFocusNode.dispose();
endFocusNode.dispose();
super.dispose();
}
void _handleChanged(RangeValues values) {
assert(_enabled);
final RangeValues lerpValues = _lerpRangeValues(values);
if (lerpValues != widget.values) {
widget.onChanged!(lerpValues);
}
}
void _actionHandler(_AdjustSliderIntent intent, Thumb thumb) {
final slider = _renderObjectKey.currentContext!.findRenderObject()! as _RenderRangeSlider;
final TextDirection directionality = Directionality.of(_renderObjectKey.currentContext!);
final bool increase = switch (intent.type) {
_SliderAdjustmentType.up => true,
_SliderAdjustmentType.down => false,
_SliderAdjustmentType.left => directionality == TextDirection.rtl,
_SliderAdjustmentType.right => directionality == TextDirection.ltr,
};
switch (thumb) {
case Thumb.start:
increase ? slider.increaseStartAction() : slider.decreaseStartAction();
case Thumb.end:
increase ? slider.increaseEndAction() : slider.decreaseEndAction();
}
}
// Toggles the value adjustment mode used by directional navigation. Entered
// and exited by pressing the enter key on a focused thumb.
void _toggleEditMode() {
setState(() {
_isEditingInDirectionalMode = !_isEditingInDirectionalMode;
});
}
// Exits the value adjustment mode when a thumb loses focus, so the slider
// does not stay in the editing state after the user navigates away.
void _handleFocusChanged(bool hasFocus) {
if (!hasFocus && _isEditingInDirectionalMode) {
setState(() {
_isEditingInDirectionalMode = false;
});
}
}
void _handleDragStart(RangeValues values) {
setState(() {
_dragging = true;
});
widget.onChangeStart?.call(_lerpRangeValues(values));
}
void _handleDragEnd(RangeValues values) {
setState(() {
_dragging = false;
});
widget.onChangeEnd?.call(_lerpRangeValues(values));
}
// 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);
final int? divisions = widget.divisions;
if (divisions != null) {
return widget.min + (value * divisions).round() * (widget.max - widget.min) / divisions;
}
return ui.lerpDouble(widget.min, widget.max, value)!;
}
// Returns a new range value with the start and end lerped.
RangeValues _lerpRangeValues(RangeValues values) {
return RangeValues(_lerp(values.start), _lerp(values.end));
}
// 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);
return widget.max > widget.min ? (value - widget.min) / (widget.max - widget.min) : 0.0;
}
// Returns a new range value with the start and end unlerped.
RangeValues _unlerpRangeValues(RangeValues values) {
return RangeValues(_unlerp(values.start), _unlerp(values.end));
}
Widget _buildThumbFocusDetector({
required FocusNode focusNode,
required Map<Type, Action<Intent>> actions,
required ValueChanged<bool> onShowFocusHighlight,
}) {
return FocusableActionDetector(
focusNode: focusNode,
enabled: _enabled,
includeFocusSemantics: false,
actions: actions,
onShowFocusHighlight: onShowFocusHighlight,
onFocusChange: _handleFocusChanged,
child: const SizedBox.shrink(),
);
}
// Finds the closest thumb. If both thumbs are close to each other and within
// the touch radius, neither is selected immediately while the drag
// displacement is zero. The first non-zero displacement determines which
// thumb is selected: a negative displacement selects the left thumb,
// a positive one selects the right thumb.
// If only one or zero thumbs are within the touch radius,
// the closest one is selected.
Thumb? _defaultRangeThumbSelector(
TextDirection textDirection,
RangeValues values,
double tapValue,
Size thumbSize,
Size trackSize,
double dx, // The horizontal delta or displacement of the drag update.
) {
final double touchRadius = math.max(thumbSize.width, RangeSlider._minTouchTargetWidth) / 2;
final bool inStartTouchTarget = (tapValue - values.start).abs() * trackSize.width < touchRadius;
final bool inEndTouchTarget = (tapValue - values.end).abs() * trackSize.width < touchRadius;
// Use dx if the thumb touch targets overlap. If dx is 0 and the drag
// position is in both touch targets, no thumb is selected because it is
// ambiguous to which thumb should be selected. If the dx is non-zero, the
// thumb selection is determined by the direction of the dx. The left thumb
// is chosen for negative dx, and the right thumb is chosen for positive dx.
if (inStartTouchTarget && inEndTouchTarget) {
final (bool towardsStart, bool towardsEnd) = switch (textDirection) {
TextDirection.ltr => (dx < 0, dx > 0),
TextDirection.rtl => (dx > 0, dx < 0),
};
if (towardsStart) {
return Thumb.start;
}
if (towardsEnd) {
return Thumb.end;
}
} else {
// Choose the closest thumb and snap position.
if (tapValue * 2 < values.start + values.end) {
return Thumb.start;
} else {
return Thumb.end;
}
}
return null;
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterial(context));
assert(debugCheckHasMediaQuery(context));
final ThemeData theme = Theme.of(context);
SliderThemeData sliderTheme = SliderTheme.of(context);
final bool year2023 = widget.year2023 ?? sliderTheme.year2023 ?? true;
final SliderThemeData defaults = theme.useMaterial3 && !year2023
? _RangeSliderDefaultsM3(context)
: _RangeSliderDefaultsM2(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
// 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.
final states = <WidgetState>{
if (!_enabled) WidgetState.disabled,
if (_hovering) WidgetState.hovered,
if (_showStartFocusHighlight || _showEndFocusHighlight) WidgetState.focused,
if (_dragging) WidgetState.dragged,
};
// 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 RangeSliderValueIndicatorShape valueIndicatorShape =
sliderTheme.rangeValueIndicatorShape ?? defaults.rangeValueIndicatorShape!;
final Color valueIndicatorColor;
if (valueIndicatorShape is RectangularRangeSliderValueIndicatorShape) {
valueIndicatorColor =
sliderTheme.valueIndicatorColor ??
Color.alphaBlend(
theme.colorScheme.onSurface.withOpacity(0.60),
theme.colorScheme.surface.withOpacity(0.90),
);
} else {
valueIndicatorColor =
widget.activeColor ?? sliderTheme.valueIndicatorColor ?? defaults.valueIndicatorColor!;
}
Color? effectiveOverlayColor() {
return widget.overlayColor?.resolve(states) ??
widget.activeColor?.withOpacity(0.12) ??
WidgetStateProperty.resolveAs<Color?>(sliderTheme.overlayColor, states) ??
defaults.overlayColor;
}
sliderTheme = sliderTheme.copyWith(
trackHeight: sliderTheme.trackHeight ?? defaults.trackHeight,
activeTrackColor:
widget.activeColor ?? sliderTheme.activeTrackColor ?? defaults.activeTrackColor,
inactiveTrackColor:
widget.inactiveColor ?? sliderTheme.inactiveTrackColor ?? defaults.inactiveTrackColor,
disabledActiveTrackColor:
sliderTheme.disabledActiveTrackColor ?? defaults.disabledActiveTrackColor,
disabledInactiveTrackColor:
sliderTheme.disabledInactiveTrackColor ?? defaults.disabledInactiveTrackColor,
activeTickMarkColor:
widget.inactiveColor ?? sliderTheme.activeTickMarkColor ?? defaults.activeTickMarkColor,
inactiveTickMarkColor:
widget.activeColor ?? sliderTheme.inactiveTickMarkColor ?? defaults.inactiveTickMarkColor,
disabledActiveTickMarkColor:
sliderTheme.disabledActiveTickMarkColor ?? defaults.disabledActiveTickMarkColor,
disabledInactiveTickMarkColor:
sliderTheme.disabledInactiveTickMarkColor ?? defaults.disabledInactiveTickMarkColor,
thumbColor: widget.activeColor ?? sliderTheme.thumbColor ?? defaults.thumbColor,
overlappingShapeStrokeColor:
sliderTheme.overlappingShapeStrokeColor ?? defaults.overlappingShapeStrokeColor,
disabledThumbColor: sliderTheme.disabledThumbColor ?? defaults.disabledThumbColor,
overlayColor: effectiveOverlayColor(),
valueIndicatorColor: valueIndicatorColor,
rangeTrackShape: sliderTheme.rangeTrackShape ?? defaults.rangeTrackShape,
rangeTickMarkShape: sliderTheme.rangeTickMarkShape ?? defaults.rangeTickMarkShape,
rangeThumbShape: sliderTheme.rangeThumbShape ?? defaults.rangeThumbShape,
overlayShape: sliderTheme.overlayShape ?? defaults.overlayShape,
rangeValueIndicatorShape: valueIndicatorShape,
showValueIndicator: sliderTheme.showValueIndicator ?? defaults.showValueIndicator,
valueIndicatorTextStyle:
sliderTheme.valueIndicatorTextStyle ?? defaults.valueIndicatorTextStyle,
minThumbSeparation: sliderTheme.minThumbSeparation ?? defaults.minThumbSeparation,
thumbSelector: sliderTheme.thumbSelector ?? _defaultRangeThumbSelector,
padding: widget.padding ?? sliderTheme.padding,
thumbSize: sliderTheme.thumbSize ?? defaults.thumbSize,
trackGap: sliderTheme.trackGap ?? defaults.trackGap,
);
final MouseCursor effectiveMouseCursor =
widget.mouseCursor?.resolve(states) ??
sliderTheme.mouseCursor?.resolve(states) ??
WidgetStateMouseCursor.clickable.resolve(states);
// 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 slider.dart.
Size screenSize() => MediaQuery.sizeOf(context);
final double fontSize = sliderTheme.valueIndicatorTextStyle?.fontSize ?? kDefaultFontSize;
final double fontSizeToScale = fontSize == 0.0 ? kDefaultFontSize : fontSize;
final double effectiveTextScale =
MediaQuery.textScalerOf(context).scale(fontSizeToScale) / fontSizeToScale;
Widget result = CompositedTransformTarget(
link: _layerLink,
child: OverlayPortal(
controller: _valueIndicatorOverlayPortalController,
overlayChildBuilder: (BuildContext context) {
return _buildValueIndicator(sliderTheme.showValueIndicator!);
},
child: _RangeSliderRenderObjectWidget(
key: _renderObjectKey,
values: _unlerpRangeValues(widget.values),
divisions: widget.divisions,
labels: widget.labels,
sliderTheme: sliderTheme,
textScaleFactor: effectiveTextScale,
screenSize: screenSize(),
onChanged: _enabled && (widget.max > widget.min) ? _handleChanged : null,
onChangeStart: _handleDragStart,
onChangeEnd: _handleDragEnd,
state: this,
semanticFormatterCallback: widget.semanticFormatterCallback,
hovering: _showHoverHighlight,
startThumbShowFocusHighlight: _showStartFocusHighlight,
endThumbShowFocusHighlight: _showEndFocusHighlight,
),
),
);
final EdgeInsetsGeometry? padding = widget.padding ?? sliderTheme.padding;
if (padding != null) {
result = Padding(padding: padding, child: result);
}
final Map<ShortcutActivator, Intent> shortcutMap = switch (_navigationMode) {
NavigationMode.directional =>
_isEditingInDirectionalMode
? _directionalNavEditingShortcutMap
: _directionalNavShortcutMap,
NavigationMode.traditional => _traditionalNavShortcutMap,
};
return Stack(
children: <Widget>[
// Adds two invisible focus nodes to the range slider for its two thumbs.
Shortcuts(
shortcuts: shortcutMap,
child: Row(
children: <Widget>[
_buildThumbFocusDetector(
focusNode: startFocusNode,
actions: _startActionMap,
onShowFocusHighlight: _handleStartFocusHighlightChanged,
),
_buildThumbFocusDetector(
focusNode: endFocusNode,
actions: _endActionMap,
onShowFocusHighlight: _handleEndFocusHighlightChanged,
),
],
),
),
MouseRegion(
onEnter: (_) => _handleHoverChanged(true),
onExit: (_) => _handleHoverChanged(false),
cursor: effectiveMouseCursor,
child: result,
),
],
);
}
final LayerLink _layerLink = LayerLink();
Widget _buildValueIndicator(ShowValueIndicator showValueIndicator) {
final Widget valueIndicator = CompositedTransformFollower(
link: _layerLink,
child: _ValueIndicatorRenderObjectWidget(state: this),