Repository navigation
Expand file tree
/
Copy pathsegmented_button.dart
More file actions
1203 lines (1111 loc) · 42.4 KB
/
Copy pathsegmented_button.dart
File metadata and controls
1203 lines (1111 loc) · 42.4 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 'checkbox.dart';
/// @docImport 'choice_chip.dart';
/// @docImport 'filter_chip.dart';
/// @docImport 'radio.dart';
/// @docImport 'toggle_buttons.dart';
library;
import 'dart:math' as math;
import 'dart:math';
import 'dart:ui' show lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'button_style.dart';
import 'button_style_button.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'constants.dart';
import 'icons.dart';
import 'ink_well.dart';
import 'material.dart';
import 'material_state.dart';
import 'segmented_button_theme.dart';
import 'text_button.dart';
import 'text_button_theme.dart';
import 'theme.dart';
import 'theme_data.dart';
import 'tooltip.dart';
part 'generated/segmented_button_defaults_m3.g.dart';
/// Data describing a segment of a [SegmentedButton].
class ButtonSegment<T> {
/// Construct a [ButtonSegment].
///
/// One of [icon] or [label] must be non-null.
const ButtonSegment({
required this.value,
this.icon,
this.label,
this.tooltip,
this.enabled = true,
}) : assert(icon != null || label != null);
/// Value used to identify the segment.
///
/// This value must be unique across all segments in a [SegmentedButton].
final T value;
/// Optional icon displayed in the segment.
final Widget? icon;
/// Optional label displayed in the segment.
final Widget? label;
/// Optional tooltip for the segment
final String? tooltip;
/// Determines if the segment is available for selection.
final bool enabled;
}
/// A Material button that allows the user to select from limited set of options.
///
/// Learn more about [SegmentedButton] on the [Flutter YouTube channel](https://www.youtube.com/watch?v=Kj6jwKsVC3A).
///
/// Segmented buttons are used to help people select options, switch views, or
/// sort elements. They are typically used in cases where there are only 2-5
/// options.
///
/// The options are represented by segments described with [ButtonSegment]
/// entries in the [segments] field. Each segment has a [ButtonSegment.value]
/// that is used to indicate which segments are selected.
///
/// The [selected] field is a set of selected [ButtonSegment.value]s. This
/// should be updated by the app in response to [onSelectionChanged] updates.
///
/// By default, only a single segment can be selected (for mutually exclusive
/// choices). This can be relaxed with the [multiSelectionEnabled] field.
///
/// Like [ButtonStyleButton]s, the [SegmentedButton]'s visuals can be
/// configured with a [ButtonStyle] [style] field. However, unlike other
/// buttons, some of the style parameters are applied to the entire segmented
/// button, and others are used for each of the segments.
///
/// By default, a checkmark icon is used to show selected items. To configure
/// this behavior, you can use the [showSelectedIcon] and [selectedIcon] fields.
///
/// Individual segments can be enabled or disabled with their
/// [ButtonSegment.enabled] flag. If the [onSelectionChanged] field is null,
/// then the entire segmented button will be disabled, regardless of the
/// individual segment settings.
///
/// <callout-box>
///
/// This sample shows how to display a [SegmentedButton] with either a single or
/// multiple selection.
///
// 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/segmented_button/segmented_button.0.dart#body}
///
/// </callout-box>
///
/// <callout-box>
///
/// This sample showcases how to customize [SegmentedButton] using [SegmentedButton.styleFrom].
///
// 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/segmented_button/segmented_button.1.dart#body}
///
/// </callout-box>
///
/// See also:
///
/// * Material Design spec: <https://m3.material.io/components/segmented-buttons/overview>
/// * [ButtonStyle], which can be used in the [style] field to configure
/// the appearance of the button and its segments.
/// * [ToggleButtons], a similar widget that was built for Material 2.
/// [SegmentedButton] should be considered as a replacement for
/// [ToggleButtons].
/// * [Radio], an alternative way to present the user with a mutually exclusive set of options.
/// * [FilterChip], [ChoiceChip], which can be used when you need to show more than five options.
class SegmentedButton<T> extends StatefulWidget {
/// Creates a const [SegmentedButton].
///
/// [segments] must contain at least one segment, but it is recommended
/// to have two to five segments. If you need only single segment,
/// consider using a [Checkbox] or [Radio] widget instead. If you need
/// more than five options, consider using [FilterChip] or [ChoiceChip]
/// widgets.
///
/// If [onSelectionChanged] is null, then the entire segmented button will
/// be disabled.
///
/// By default [selected] must only contain one entry. However, if
/// [multiSelectionEnabled] is true, then [selected] can contain multiple
/// entries. If [emptySelectionAllowed] is true, then [selected] can be empty.
const SegmentedButton({
super.key,
required this.segments,
required this.selected,
this.onSelectionChanged,
this.multiSelectionEnabled = false,
this.emptySelectionAllowed = false,
this.expandedInsets,
this.style,
this.showSelectedIcon = true,
this.selectedIcon,
this.direction = Axis.horizontal,
}) : assert(segments.length > 0),
assert(selected.length > 0 || emptySelectionAllowed),
assert(selected.length < 2 || multiSelectionEnabled);
/// Descriptions of the segments in the button.
///
/// This a required parameter and must contain at least one segment,
/// but it is recommended to contain two to five segments. If you need only
/// a single segment, consider using a [Checkbox] or [Radio] widget instead.
/// If you need more than five options, consider using [FilterChip] or
/// [ChoiceChip] widgets.
final List<ButtonSegment<T>> segments;
/// The orientation of the button's [segments].
///
/// If this is [Axis.vertical], the segments will be aligned vertically
/// and the first item in [segments] will be on the top.
///
/// Defaults to [Axis.horizontal].
final Axis direction;
/// The set of [ButtonSegment.value]s that indicate which [segments] are
/// selected.
///
/// As the [SegmentedButton] does not maintain the state of the selection,
/// you will need to update this in response to [onSelectionChanged] calls.
///
/// This is a required parameter.
final Set<T> selected;
/// The function that is called when the selection changes.
///
/// The callback's parameter indicates which of the segments are selected.
///
/// When the callback is null, the entire [SegmentedButton] is disabled,
/// and will not respond to input.
///
/// The default is null.
final void Function(Set<T>)? onSelectionChanged;
/// Determines if multiple segments can be selected at one time.
///
/// If true, more than one segment can be selected. When selecting a
/// segment, the other selected segments will stay selected. Selecting an
/// already selected segment will unselect it.
///
/// If false, only one segment may be selected at a time. When a segment
/// is selected, any previously selected segment will be unselected.
///
/// The default is false, so only a single segment may be selected at one
/// time.
final bool multiSelectionEnabled;
/// Determines if having no selected segments is allowed.
///
/// If true, then it is acceptable for none of the segments to be selected.
/// This means that [selected] can be empty. If the user taps on a
/// selected segment, it will be removed from the selection set passed into
/// [onSelectionChanged].
///
/// If false (the default), there must be at least one segment selected. If
/// the user taps on the only selected segment it will not be deselected, and
/// [onSelectionChanged] will not be called.
final bool emptySelectionAllowed;
/// Determines the segmented button's size and padding based on [expandedInsets].
///
/// If null (default), the button adopts its intrinsic content size. When specified,
/// the button expands to fill its parent's space, with the [EdgeInsets]
/// defining the padding.
final EdgeInsets? expandedInsets;
/// A static convenience method that constructs a segmented button
/// [ButtonStyle] given simple values.
///
/// The [foregroundColor], [selectedForegroundColor], and [disabledForegroundColor]
/// colors are used to create a [WidgetStateProperty] [ButtonStyle.foregroundColor],
/// and a derived [ButtonStyle.overlayColor] if [overlayColor] isn't specified.
///
/// If [overlayColor] is specified and its value is [Colors.transparent]
/// then the pressed/focused/hovered highlights are effectively defeated.
/// Otherwise a [WidgetStateProperty] with the same opacities as the
/// default is created.
///
/// The [backgroundColor], [selectedBackgroundColor] and [disabledBackgroundColor]
/// colors are used to create a [WidgetStateProperty] [ButtonStyle.backgroundColor].
///
/// Similarly, the [enabledMouseCursor] and [disabledMouseCursor]
/// parameters are used to construct [ButtonStyle.mouseCursor].
///
/// The [iconColor], [disabledIconColor] are used to construct
/// [ButtonStyle.iconColor] and [iconSize] is used to construct
/// [ButtonStyle.iconSize].
///
/// All of the other parameters are either used directly or used to
/// create a [WidgetStateProperty] with a single value for all
/// states.
///
/// All parameters default to null. By default this method returns
/// a [ButtonStyle] that doesn't override anything.
///
/// <callout-box>
///
// TODO(framework): Add unit tests to this code snippet.
// https://github.com/flutter/flutter/issues/188530
///
/// For example, to override the default text and icon colors for a
/// [SegmentedButton], as well as its overlay color, with all of the
/// standard opacity adjustments for the pressed, focused, and
/// hovered states, one could write:
///
/// {@example /example/lib/segmented_button/segmented_button.1.dart#body}
///
/// ```dart
/// SegmentedButton<int>(
/// style: SegmentedButton.styleFrom(
/// foregroundColor: Colors.black,
/// selectedForegroundColor: Colors.white,
/// backgroundColor: Colors.amber,
/// selectedBackgroundColor: Colors.red,
/// ),
/// segments: const <ButtonSegment<int>>[
/// ButtonSegment<int>(
/// value: 0,
/// label: Text('0'),
/// icon: Icon(Icons.calendar_view_day),
/// ),
/// ButtonSegment<int>(
/// value: 1,
/// label: Text('1'),
/// icon: Icon(Icons.calendar_view_week),
/// ),
/// ],
/// selected: const <int>{0},
/// onSelectionChanged: (Set<int> selection) {},
/// ),
/// ```
///
/// </callout-box>
static ButtonStyle styleFrom({
Color? foregroundColor,
Color? backgroundColor,
Color? selectedForegroundColor,
Color? selectedBackgroundColor,
Color? disabledForegroundColor,
Color? disabledBackgroundColor,
Color? shadowColor,
Color? surfaceTintColor,
Color? iconColor,
double? iconSize,
Color? disabledIconColor,
Color? overlayColor,
double? elevation,
TextStyle? textStyle,
EdgeInsetsGeometry? padding,
Size? minimumSize,
Size? fixedSize,
Size? maximumSize,
BorderSide? side,
OutlinedBorder? shape,
MouseCursor? enabledMouseCursor,
MouseCursor? disabledMouseCursor,
VisualDensity? visualDensity,
MaterialTapTargetSize? tapTargetSize,
Duration? animationDuration,
bool? enableFeedback,
AlignmentGeometry? alignment,
InteractiveInkFeatureFactory? splashFactory,
}) {
final WidgetStateProperty<Color?>? overlayColorProp =
(foregroundColor == null && selectedForegroundColor == null && overlayColor == null)
? null
: switch (overlayColor) {
(final Color overlayColor) when overlayColor.value == 0 =>
const WidgetStatePropertyAll<Color?>(Colors.transparent),
_ => _SegmentedButtonDefaultsM3.resolveStateColor(
foregroundColor,
selectedForegroundColor,
overlayColor,
),
};
return TextButton.styleFrom(
textStyle: textStyle,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
iconColor: iconColor,
iconSize: iconSize,
disabledIconColor: disabledIconColor,
elevation: elevation,
padding: padding,
minimumSize: minimumSize,
fixedSize: fixedSize,
maximumSize: maximumSize,
side: side,
shape: shape,
enabledMouseCursor: enabledMouseCursor,
disabledMouseCursor: disabledMouseCursor,
visualDensity: visualDensity,
tapTargetSize: tapTargetSize,
animationDuration: animationDuration,
enableFeedback: enableFeedback,
alignment: alignment,
splashFactory: splashFactory,
).copyWith(
foregroundColor: _defaultColor(
foregroundColor,
disabledForegroundColor,
selectedForegroundColor,
),
backgroundColor: _defaultColor(
backgroundColor,
disabledBackgroundColor,
selectedBackgroundColor,
),
overlayColor: overlayColorProp,
);
}
static WidgetStateProperty<Color?>? _defaultColor(
Color? enabled,
Color? disabled,
Color? selected,
) {
if ((selected ?? enabled ?? disabled) == null) {
return null;
}
return WidgetStateProperty<Color?>.fromMap(<WidgetStatesConstraint, Color?>{
WidgetState.disabled: disabled,
WidgetState.selected: selected,
WidgetState.any: enabled,
});
}
/// Customizes this button's appearance.
///
/// The following style properties apply to the entire segmented button:
///
/// * [ButtonStyle.shadowColor]
/// * [ButtonStyle.elevation]
/// * [ButtonStyle.side] - which is used for both the outer shape and
/// dividers between segments.
/// * [ButtonStyle.shape]
///
/// The following style properties are applied to each of the individual
/// button segments. For properties that are a [WidgetStateProperty],
/// they will be resolved with the current state of the segment:
///
/// * [ButtonStyle.textStyle]
/// * [ButtonStyle.backgroundColor]
/// * [ButtonStyle.foregroundColor]
/// * [ButtonStyle.overlayColor]
/// * [ButtonStyle.surfaceTintColor]
/// * [ButtonStyle.elevation]
/// * [ButtonStyle.padding]
/// * [ButtonStyle.iconColor]
/// * [ButtonStyle.iconSize]
/// * [ButtonStyle.mouseCursor]
/// * [ButtonStyle.visualDensity]
/// * [ButtonStyle.tapTargetSize]
/// * [ButtonStyle.animationDuration]
/// * [ButtonStyle.enableFeedback]
/// * [ButtonStyle.alignment]
/// * [ButtonStyle.splashFactory]
///
/// If [ButtonStyle.side] is provided, [WidgetStateProperty.resolve] is used
/// for the following [WidgetState]s:
///
/// * [WidgetState.focused].
/// * [WidgetState.hovered].
/// * [WidgetState.disabled].
/// * [WidgetState.selected].
final ButtonStyle? style;
/// Determines if the [selectedIcon] (usually an icon using [Icons.check])
/// is displayed on the selected segments.
///
/// If true, the [selectedIcon] will be displayed at the start of the segment.
/// If both the [ButtonSegment.label] and [ButtonSegment.icon] are provided,
/// then the icon will be replaced with the [selectedIcon]. If only the icon
/// or the label is present then the [selectedIcon] will be shown at the start
/// of the segment.
///
/// If false, then the [selectedIcon] is not used and will not be displayed
/// on selected segments.
///
/// The default is true, meaning the [selectedIcon] will be shown on selected
/// segments.
final bool showSelectedIcon;
/// An icon that is used to indicate a segment is selected.
///
/// If [showSelectedIcon] is true then for selected segments this icon
/// will be shown before the [ButtonSegment.label], replacing the
/// [ButtonSegment.icon] if it is specified.
///
/// Defaults to an [Icon] with [Icons.check].
final Widget? selectedIcon;
@override
State<SegmentedButton<T>> createState() => SegmentedButtonState<T>();
}
/// State for [SegmentedButton].
@visibleForTesting
class SegmentedButtonState<T> extends State<SegmentedButton<T>> {
bool get _enabled => widget.onSelectionChanged != null;
bool _hovering = false;
bool _focused = false;
bool get _selected => widget.selected.isNotEmpty;
Set<WidgetState> get _states => <WidgetState>{
if (!_enabled) WidgetState.disabled,
if (_hovering) WidgetState.hovered,
if (_focused) WidgetState.focused,
if (_selected) WidgetState.selected,
};
/// Controllers for the [ButtonSegment]s.
@visibleForTesting
final Map<ButtonSegment<T>, MaterialStatesController> statesControllers =
<ButtonSegment<T>, MaterialStatesController>{};
@protected
@override
void didUpdateWidget(covariant SegmentedButton<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget != widget) {
statesControllers.removeWhere((
ButtonSegment<T> segment,
MaterialStatesController controller,
) {
if (widget.segments.contains(segment)) {
return false;
} else {
controller.dispose();
return true;
}
});
}
}
void _handleOnPressed(T segmentValue) {
if (!_enabled) {
return;
}
final bool onlySelectedSegment =
widget.selected.length == 1 && widget.selected.contains(segmentValue);
final bool validChange = widget.emptySelectionAllowed || !onlySelectedSegment;
if (validChange) {
final bool toggle =
widget.multiSelectionEnabled || (widget.emptySelectionAllowed && onlySelectedSegment);
final pressedSegment = <T>{segmentValue};
late final Set<T> updatedSelection;
if (toggle) {
updatedSelection = widget.selected.contains(segmentValue)
? widget.selected.difference(pressedSegment)
: widget.selected.union(pressedSegment);
} else {
updatedSelection = pressedSegment;
}
if (!setEquals(updatedSelection, widget.selected)) {
widget.onSelectionChanged!(updatedSelection);
}
}
}
@protected
@override
Widget build(BuildContext context) {
final SegmentedButtonThemeData theme = SegmentedButtonTheme.of(context);
final SegmentedButtonThemeData defaults = _SegmentedButtonDefaultsM3(context);
final TextDirection textDirection = Directionality.of(context);
const disabledState = <WidgetState>{WidgetState.disabled};
P? effectiveValue<P>(P? Function(ButtonStyle? style) getProperty) {
late final P? widgetValue = getProperty(widget.style);
late final P? themeValue = getProperty(theme.style);
late final P? defaultValue = getProperty(defaults.style);
return widgetValue ?? themeValue ?? defaultValue;
}
P? resolve<P>(
WidgetStateProperty<P>? Function(ButtonStyle? style) getProperty, [
Set<WidgetState>? states,
]) {
return effectiveValue((ButtonStyle? style) => getProperty(style)?.resolve(states ?? _states));
}
ButtonStyle segmentStyleFor(ButtonStyle? style) {
return ButtonStyle(
textStyle: style?.textStyle,
backgroundColor: style?.backgroundColor,
foregroundColor: style?.foregroundColor,
overlayColor: style?.overlayColor,
surfaceTintColor: style?.surfaceTintColor,
elevation: style?.elevation,
padding: style?.padding,
iconColor: style?.iconColor,
iconSize: style?.iconSize,
shape: const WidgetStatePropertyAll<OutlinedBorder>(RoundedRectangleBorder()),
mouseCursor: style?.mouseCursor,
visualDensity: style?.visualDensity,
tapTargetSize: style?.tapTargetSize,
animationDuration: style?.animationDuration,
enableFeedback: style?.enableFeedback,
alignment: style?.alignment,
splashFactory: style?.splashFactory,
);
}
final ButtonStyle segmentStyle = segmentStyleFor(widget.style);
final ButtonStyle segmentThemeStyle = segmentStyleFor(theme.style)
.merge(segmentStyleFor(defaults.style));
final Widget? selectedIcon = widget.showSelectedIcon
? widget.selectedIcon ?? theme.selectedIcon ?? defaults.selectedIcon
: null;
Widget buttonFor(ButtonSegment<T> segment) {
final Widget label = segment.label ?? segment.icon ?? const SizedBox.shrink();
final bool segmentSelected = widget.selected.contains(segment.value);
final Widget? icon = (segmentSelected && widget.showSelectedIcon)
? selectedIcon
: segment.label != null
? segment.icon
: null;
final MaterialStatesController controller = statesControllers.putIfAbsent(
segment,
() => MaterialStatesController(),
);
controller.update(WidgetState.selected, segmentSelected);
var content = label;
var effectiveSegmentStyle = segmentStyle;
if (icon != null) {
// This logic is needed to get the exact same rendering as using TextButton.icon.
// It is duplicated from _TextButtonWithIcon and _TextButtonWithIconChild.
// TODO(bleroux): remove once https://github.com/flutter/flutter/issues/173944 is fixed.
final bool useMaterial3 = Theme.of(context).useMaterial3;
final double defaultFontSize =
segmentStyle.textStyle?.resolve(const <WidgetState>{})?.fontSize ?? 14.0;
final double effectiveTextScale =
MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0;
final EdgeInsetsGeometry scaledPadding = ButtonStyleButton.scaledPadding(
useMaterial3
? const EdgeInsetsDirectional.fromSTEB(12, 8, 16, 8)
: const EdgeInsets.all(8),
const EdgeInsets.symmetric(horizontal: 4),
const EdgeInsets.symmetric(horizontal: 4),
effectiveTextScale,
);
effectiveSegmentStyle = segmentStyle.copyWith(
padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(scaledPadding),
);
final double scale = clampDouble(effectiveTextScale, 1.0, 2.0) - 1.0;
final TextButtonThemeData textButtonTheme = TextButtonTheme.of(context);
final IconAlignment effectiveIconAlignment =
textButtonTheme.style?.iconAlignment ??
segmentStyle.iconAlignment ??
IconAlignment.start;
content = Row(
mainAxisSize: MainAxisSize.min,
spacing: lerpDouble(8, 4, scale)!,
children: effectiveIconAlignment == IconAlignment.start
? <Widget>[icon, Flexible(child: label)]
: <Widget>[Flexible(child: label), icon],
);
}
final Widget button = TextButton(
style: effectiveSegmentStyle,
statesController: controller,
onHover: (bool hovering) {
setState(() {
_hovering = hovering;
});
},
onFocusChange: (bool focused) {
setState(() {
_focused = focused;
});
},
onPressed: (_enabled && segment.enabled) ? () => _handleOnPressed(segment.value) : null,
child: content,
);
final Widget buttonWithTooltip = segment.tooltip != null
? Tooltip(message: segment.tooltip, child: button)
: button;
return MergeSemantics(
child: Semantics(
selected: segmentSelected,
inMutuallyExclusiveGroup: widget.multiSelectionEnabled ? null : true,
child: buttonWithTooltip,
),
);
}
final OutlinedBorder effectiveBorder =
resolve<OutlinedBorder?>((ButtonStyle? style) => style?.shape) ??
const RoundedRectangleBorder();
final OutlinedBorder resolvedDisabledBorder =
resolve<OutlinedBorder?>((ButtonStyle? style) => style?.shape, disabledState) ??
const RoundedRectangleBorder();
final BorderSide effectiveSide =
resolve<BorderSide?>((ButtonStyle? style) => style?.side) ?? BorderSide.none;
final BorderSide disabledSide =
resolve<BorderSide?>((ButtonStyle? style) => style?.side, disabledState) ?? BorderSide.none;
final OutlinedBorder enabledBorder = effectiveBorder.copyWith(side: effectiveSide);
final OutlinedBorder disabledBorder = resolvedDisabledBorder.copyWith(side: disabledSide);
final VisualDensity resolvedVisualDensity =
segmentStyle.visualDensity ??
segmentThemeStyle.visualDensity ??
Theme.of(context).visualDensity;
final EdgeInsetsGeometry resolvedPadding =
resolve<EdgeInsetsGeometry?>((ButtonStyle? style) => style?.padding) ?? EdgeInsets.zero;
final MaterialTapTargetSize resolvedTapTargetSize =
segmentStyle.tapTargetSize ??
segmentThemeStyle.tapTargetSize ??
Theme.of(context).materialTapTargetSize;
final double fontSize =
resolve<TextStyle?>((ButtonStyle? style) => style?.textStyle)?.fontSize ?? 20.0;
final List<Widget> buttons = widget.segments.map(buttonFor).toList();
final Offset densityAdjustment = resolvedVisualDensity.baseSizeAdjustment;
const textButtonMinHeight = 40.0;
final double adjustButtonMinHeight = textButtonMinHeight + densityAdjustment.dy;
final double effectiveVerticalPadding = resolvedPadding.vertical + densityAdjustment.dy * 2;
final double effectedButtonHeight = max(
fontSize + effectiveVerticalPadding,
adjustButtonMinHeight,
);
final double tapTargetVerticalPadding = switch (resolvedTapTargetSize) {
MaterialTapTargetSize.shrinkWrap => 0.0,
MaterialTapTargetSize.padded => max(
0,
kMinInteractiveDimension + densityAdjustment.dy - effectedButtonHeight,
),
};
return Material(
type: MaterialType.transparency,
elevation: resolve<double?>((ButtonStyle? style) => style?.elevation)!,
shadowColor: resolve<Color?>((ButtonStyle? style) => style?.shadowColor),
surfaceTintColor: resolve<Color?>((ButtonStyle? style) => style?.surfaceTintColor),
child: TextButtonTheme(
data: TextButtonThemeData(style: segmentThemeStyle),
child: Padding(
padding: widget.expandedInsets ?? EdgeInsets.zero,
child: _SegmentedButtonRenderWidget<T>(
tapTargetVerticalPadding: tapTargetVerticalPadding,
segments: widget.segments,
enabledBorder: _enabled ? enabledBorder : disabledBorder,
disabledBorder: disabledBorder,
direction: widget.direction,
textDirection: textDirection,
isExpanded: widget.expandedInsets != null,
children: buttons,
),
),
),
);
}
@protected
@override
void dispose() {
for (final MaterialStatesController controller in statesControllers.values) {
controller.dispose();
}
super.dispose();
}
}
class _SegmentedButtonRenderWidget<T> extends MultiChildRenderObjectWidget {
const _SegmentedButtonRenderWidget({
required this.segments,
required this.enabledBorder,
required this.disabledBorder,
required this.direction,
required this.textDirection,
required this.tapTargetVerticalPadding,
required this.isExpanded,
required super.children,
}) : assert(children.length == segments.length);
final List<ButtonSegment<T>> segments;
final OutlinedBorder enabledBorder;
final OutlinedBorder disabledBorder;
final Axis direction;
final TextDirection textDirection;
final double tapTargetVerticalPadding;
final bool isExpanded;
@override
RenderObject createRenderObject(BuildContext context) {
return _RenderSegmentedButton<T>(
segments: segments,
enabledBorder: enabledBorder,
disabledBorder: disabledBorder,
textDirection: textDirection,
direction: direction,
tapTargetVerticalPadding: tapTargetVerticalPadding,
isExpanded: isExpanded,
);
}
@override
void updateRenderObject(BuildContext context, _RenderSegmentedButton<T> renderObject) {
renderObject
..segments = segments
..enabledBorder = enabledBorder
..disabledBorder = disabledBorder
..direction = direction
..textDirection = textDirection;
}
}
class _SegmentedButtonContainerBoxParentData extends ContainerBoxParentData<RenderBox> {
RRect? surroundingRect;
}
typedef _NextChild = RenderBox? Function(RenderBox child);
class _RenderSegmentedButton<T> extends RenderBox
with
ContainerRenderObjectMixin<RenderBox, ContainerBoxParentData<RenderBox>>,
RenderBoxContainerDefaultsMixin<RenderBox, ContainerBoxParentData<RenderBox>> {
_RenderSegmentedButton({
required this._segments,
required this._enabledBorder,
required this._disabledBorder,
required this._textDirection,
required this._tapTargetVerticalPadding,
required this._isExpanded,
required this._direction,
});
List<ButtonSegment<T>> get segments => _segments;
List<ButtonSegment<T>> _segments;
set segments(List<ButtonSegment<T>> value) {
if (listEquals(segments, value)) {
return;
}
_segments = value;
markNeedsLayout();
}
OutlinedBorder get enabledBorder => _enabledBorder;
OutlinedBorder _enabledBorder;
set enabledBorder(OutlinedBorder value) {
if (_enabledBorder == value) {
return;
}
_enabledBorder = value;
markNeedsLayout();
}
OutlinedBorder get disabledBorder => _disabledBorder;
OutlinedBorder _disabledBorder;
set disabledBorder(OutlinedBorder value) {
if (_disabledBorder == value) {
return;
}
_disabledBorder = value;
markNeedsLayout();
}
TextDirection get textDirection => _textDirection;
TextDirection _textDirection;
set textDirection(TextDirection value) {
if (value == _textDirection) {
return;
}
_textDirection = value;
markNeedsLayout();
}
Axis get direction => _direction;
Axis _direction;
set direction(Axis value) {
if (value == _direction) {
return;
}
_direction = value;
markNeedsLayout();
}
double get tapTargetVerticalPadding => _tapTargetVerticalPadding;
double _tapTargetVerticalPadding;
set tapTargetVerticalPadding(double value) {
if (value == _tapTargetVerticalPadding) {
return;
}
_tapTargetVerticalPadding = value;
markNeedsLayout();
}
bool get isExpanded => _isExpanded;
bool _isExpanded;
set isExpanded(bool value) {
if (value == _isExpanded) {
return;
}
_isExpanded = value;
markNeedsLayout();
}
@override
double computeMinIntrinsicWidth(double height) {
RenderBox? child = firstChild;
var minWidth = 0.0;
while (child != null) {
final childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData;
final double childWidth = child.getMinIntrinsicWidth(height);
minWidth = math.max(minWidth, childWidth);
child = childParentData.nextSibling;
}
return minWidth * childCount;
}
@override
double computeMaxIntrinsicWidth(double height) {
RenderBox? child = firstChild;
var maxWidth = 0.0;
while (child != null) {
final childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData;
final double childWidth = child.getMaxIntrinsicWidth(height);
maxWidth = math.max(maxWidth, childWidth);
child = childParentData.nextSibling;
}
return maxWidth * childCount;
}
@override
double computeMinIntrinsicHeight(double width) {
RenderBox? child = firstChild;
var minHeight = 0.0;
while (child != null) {
final childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData;
final double childHeight = child.getMinIntrinsicHeight(width);
minHeight = math.max(minHeight, childHeight);
child = childParentData.nextSibling;
}
return minHeight;
}
@override
double computeMaxIntrinsicHeight(double width) {
RenderBox? child = firstChild;
var maxHeight = 0.0;
while (child != null) {
final childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData;
final double childHeight = child.getMaxIntrinsicHeight(width);
maxHeight = math.max(maxHeight, childHeight);
child = childParentData.nextSibling;
}
return maxHeight;
}
@override
double? computeDistanceToActualBaseline(TextBaseline baseline) {
return defaultComputeDistanceToHighestActualBaseline(baseline);
}
@override
void setupParentData(RenderBox child) {
if (child.parentData is! _SegmentedButtonContainerBoxParentData) {
child.parentData = _SegmentedButtonContainerBoxParentData();
}
}
void _layoutRects(_NextChild nextChild, RenderBox? leftChild, RenderBox? rightChild) {
var child = leftChild;
var start = 0.0;
while (child != null) {
final childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData;
late final RRect rChildRect;
if (direction == Axis.vertical) {
childParentData.offset = Offset(0.0, start);
final childRect = Rect.fromLTWH(
0.0,
childParentData.offset.dy,
child.size.width,
child.size.height,
);
rChildRect = RRect.fromRectAndCorners(childRect);
start += child.size.height;
} else {
childParentData.offset = Offset(start, 0.0);
final childRect = Rect.fromLTWH(start, 0.0, child.size.width, child.size.height);
rChildRect = RRect.fromRectAndCorners(childRect);
start += child.size.width;
}
childParentData.surroundingRect = rChildRect;
child = nextChild(child);
}
}
Size _calculateChildSize(BoxConstraints constraints) {
return direction == Axis.horizontal
? _calculateHorizontalChildSize(constraints)
: _calculateVerticalChildSize(constraints);
}
Size _calculateHorizontalChildSize(BoxConstraints constraints) {
double maxHeight = 0;
RenderBox? child = firstChild;
double childWidth;
if (_isExpanded) {
childWidth = constraints.maxWidth / childCount;
} else {
childWidth = constraints.minWidth / childCount;
while (child != null) {
childWidth = math.max(childWidth, child.getMaxIntrinsicWidth(double.infinity));
child = childAfter(child);
}
childWidth = math.min(childWidth, constraints.maxWidth / childCount);
}
child = firstChild;
while (child != null) {
final double boxHeight = child.getMaxIntrinsicHeight(childWidth);
maxHeight = math.max(maxHeight, boxHeight);
child = childAfter(child);
}
return Size(childWidth, maxHeight);
}
Size _calculateVerticalChildSize(BoxConstraints constraints) {
double maxWidth = 0;
RenderBox? child = firstChild;
double childHeight;
if (_isExpanded) {
childHeight = constraints.maxHeight / childCount;
} else {
childHeight = constraints.minHeight / childCount;