-
Notifications
You must be signed in to change notification settings - Fork 30.3k
Expand file tree
/
Copy pathdropdown.dart
More file actions
2014 lines (1834 loc) · 70.9 KB
/
dropdown.dart
File metadata and controls
2014 lines (1834 loc) · 70.9 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 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// @docImport 'data_table.dart';
/// @docImport 'dropdown_menu.dart';
/// @docImport 'elevated_button.dart';
/// @docImport 'scaffold.dart';
/// @docImport 'text_button.dart';
/// @docImport 'text_theme.dart';
library;
import 'dart:math' as math;
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'button_theme.dart';
import 'colors.dart';
import 'constants.dart';
import 'debug.dart';
import 'icons.dart';
import 'ink_decoration.dart';
import 'ink_well.dart';
import 'input_decorator.dart';
import 'material.dart';
import 'material_localizations.dart';
import 'scrollbar.dart';
import 'shadows.dart';
import 'theme.dart';
const Duration _kDropdownMenuDuration = Duration(milliseconds: 300);
const double _kMenuItemHeight = kMinInteractiveDimension;
const double _kDenseButtonHeight = 24.0;
const EdgeInsets _kMenuItemPadding = EdgeInsets.symmetric(horizontal: 16.0);
const EdgeInsetsGeometry _kAlignedButtonPadding = EdgeInsetsDirectional.only(start: 16.0, end: 4.0);
const EdgeInsets _kUnalignedButtonPadding = EdgeInsets.zero;
const EdgeInsets _kAlignedMenuMargin = EdgeInsets.zero;
const EdgeInsetsGeometry _kUnalignedMenuMargin = EdgeInsetsDirectional.only(start: 16.0, end: 24.0);
/// A builder to customize dropdown buttons.
///
/// Used by [DropdownButton.selectedItemBuilder].
///
/// The list of widgets returned by this builder must be exactly the same length
/// as the [DropdownButton.items] list.
typedef DropdownButtonBuilder = List<Widget> Function(BuildContext context);
class _DropdownMenuPainter extends CustomPainter {
_DropdownMenuPainter({
this.color,
this.elevation,
this.selectedIndex,
this.borderRadius,
required this.resize,
required this.getSelectedItemOffset,
}) : _painter = BoxDecoration(
// If you add an image here, you must provide a real
// configuration in the paint() function and you must provide some sort
// of onChanged callback here.
color: color,
borderRadius: borderRadius ?? const BorderRadius.all(Radius.circular(2.0)),
boxShadow: kElevationToShadow[elevation],
).createBoxPainter(),
super(repaint: resize);
final Color? color;
final int? elevation;
final int? selectedIndex;
final BorderRadius? borderRadius;
final Animation<double> resize;
final ValueGetter<double> getSelectedItemOffset;
final BoxPainter _painter;
@override
void paint(Canvas canvas, Size size) {
final double selectedItemOffset = getSelectedItemOffset();
final top = Tween<double>(
begin: clampDouble(selectedItemOffset, 0.0, math.max(size.height - _kMenuItemHeight, 0.0)),
end: 0.0,
);
final bottom = Tween<double>(
begin: clampDouble(
top.begin! + _kMenuItemHeight,
math.min(_kMenuItemHeight, size.height),
size.height,
),
end: size.height,
);
final rect = Rect.fromLTRB(0.0, top.evaluate(resize), size.width, bottom.evaluate(resize));
_painter.paint(canvas, rect.topLeft, ImageConfiguration(size: rect.size));
}
@override
bool shouldRepaint(_DropdownMenuPainter oldPainter) {
return oldPainter.color != color ||
oldPainter.elevation != elevation ||
oldPainter.selectedIndex != selectedIndex ||
oldPainter.borderRadius != borderRadius ||
oldPainter.resize != resize;
}
}
// The widget that is the button wrapping the menu items.
class _DropdownMenuItemButton<T> extends StatefulWidget {
const _DropdownMenuItemButton({
super.key,
this.padding,
required this.route,
required this.buttonRect,
required this.constraints,
required this.itemIndex,
required this.enableFeedback,
required this.scrollController,
this.mouseCursor,
});
final _DropdownRoute<T> route;
final ScrollController scrollController;
final EdgeInsets? padding;
final Rect buttonRect;
final BoxConstraints constraints;
final int itemIndex;
final bool enableFeedback;
final MouseCursor? mouseCursor;
@override
_DropdownMenuItemButtonState<T> createState() => _DropdownMenuItemButtonState<T>();
}
class _DropdownMenuItemButtonState<T> extends State<_DropdownMenuItemButton<T>> {
late CurvedAnimation _opacityAnimation;
@override
void initState() {
super.initState();
_setOpacityAnimation();
}
@override
void didUpdateWidget(_DropdownMenuItemButton<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.itemIndex != widget.itemIndex ||
oldWidget.route.animation != widget.route.animation ||
oldWidget.route.selectedIndex != widget.route.selectedIndex ||
widget.route.items.length != oldWidget.route.items.length) {
_opacityAnimation.dispose();
_setOpacityAnimation();
}
}
void _setOpacityAnimation() {
final double unit = 0.5 / (widget.route.items.length + 1.5);
if (widget.itemIndex == widget.route.selectedIndex) {
_opacityAnimation = CurvedAnimation(
parent: widget.route.animation!,
curve: const Threshold(0.0),
);
} else {
final double start = clampDouble(0.5 + (widget.itemIndex + 1) * unit, 0.0, 1.0);
final double end = clampDouble(start + 1.5 * unit, 0.0, 1.0);
_opacityAnimation = CurvedAnimation(
parent: widget.route.animation!,
curve: Interval(start, end),
);
}
}
void _handleFocusChange(bool focused) {
final bool inTraditionalMode = switch (FocusManager.instance.highlightMode) {
FocusHighlightMode.touch => false,
FocusHighlightMode.traditional => true,
};
if (focused && inTraditionalMode) {
final _MenuLimits menuLimits = widget.route.getMenuLimits(
widget.buttonRect,
widget.constraints.maxHeight,
widget.itemIndex,
);
widget.scrollController.animateTo(
menuLimits.scrollOffset,
curve: Curves.easeInOut,
duration: const Duration(milliseconds: 100),
);
}
}
void _handleOnTap() {
final DropdownMenuItem<T> dropdownMenuItem = widget.route.items[widget.itemIndex].item!;
dropdownMenuItem.onTap?.call();
Navigator.pop(context, _DropdownRouteResult<T>(dropdownMenuItem.value));
}
static const Map<ShortcutActivator, Intent> _webShortcuts = <ShortcutActivator, Intent>{
// On the web, up/down don't change focus, *except* in a <select>
// element, which is what a dropdown emulates.
SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down),
SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up),
};
@override
void dispose() {
_opacityAnimation.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final DropdownMenuItem<T> dropdownMenuItem = widget.route.items[widget.itemIndex].item!;
Widget child = widget.route.items[widget.itemIndex];
if (widget.padding case final EdgeInsetsGeometry padding) {
child = Padding(padding: padding, child: child);
}
child = SizedBox(height: widget.route.itemHeight, child: child);
final isSelected = widget.itemIndex == widget.route.selectedIndex;
final FocusHighlightMode highlightMode = FocusManager.instance.highlightMode;
// An [InkWell] is added to the item only if it is enabled
if (dropdownMenuItem.enabled) {
child = InkWell(
autofocus: isSelected,
enableFeedback: widget.enableFeedback,
onTap: _handleOnTap,
onFocusChange: _handleFocusChange,
mouseCursor: widget.mouseCursor,
// When highlightMode is traditional, the InkWell draws the selected item background color.
// When highlightMode is touch, insert an Ink to force the selected item background color.
child: highlightMode == FocusHighlightMode.touch
? Ink(color: isSelected ? Theme.of(context).focusColor : null, child: child)
: child,
);
}
child = FadeTransition(opacity: _opacityAnimation, child: child);
if (kIsWeb && dropdownMenuItem.enabled) {
child = Shortcuts(shortcuts: _webShortcuts, child: child);
}
return Semantics(role: SemanticsRole.menuItem, child: child);
}
}
class _DropdownMenu<T> extends StatefulWidget {
const _DropdownMenu({
super.key,
this.padding,
required this.route,
required this.buttonRect,
required this.constraints,
this.dropdownColor,
required this.enableFeedback,
this.borderRadius,
required this.scrollController,
this.menuWidth,
this.mouseCursor,
});
final _DropdownRoute<T> route;
final EdgeInsets? padding;
final Rect buttonRect;
final BoxConstraints constraints;
final Color? dropdownColor;
final bool enableFeedback;
final BorderRadius? borderRadius;
final ScrollController scrollController;
final double? menuWidth;
final MouseCursor? mouseCursor;
@override
_DropdownMenuState<T> createState() => _DropdownMenuState<T>();
}
class _DropdownMenuState<T> extends State<_DropdownMenu<T>> {
late final CurvedAnimation _fadeOpacity;
late final CurvedAnimation _resize;
@override
void initState() {
super.initState();
// We need to hold these animations as state because of their curve
// direction. When the route's animation reverses, if we were to recreate
// the CurvedAnimation objects in build, we'd lose
// CurvedAnimation._curveDirection.
_fadeOpacity = CurvedAnimation(
parent: widget.route.animation!,
curve: const Interval(0.0, 0.25),
reverseCurve: const Interval(0.75, 1.0),
);
_resize = CurvedAnimation(
parent: widget.route.animation!,
curve: const Interval(0.25, 0.5),
reverseCurve: const Threshold(0.0),
);
}
@override
void dispose() {
_fadeOpacity.dispose();
_resize.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
// The menu is shown in three stages (unit timing in brackets):
// [0s - 0.25s] - Fade in a rect-sized menu container with the selected item.
// [0.25s - 0.5s] - Grow the otherwise empty menu container from the center
// until it's big enough for as many items as we're going to show.
// [0.5s - 1.0s] Fade in the remaining visible items from top to bottom.
//
// When the menu is dismissed we just fade the entire thing out
// in the first 0.25s.
assert(debugCheckHasMaterialLocalizations(context));
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final _DropdownRoute<T> route = widget.route;
final children = <Widget>[
for (int itemIndex = 0; itemIndex < route.items.length; ++itemIndex)
_DropdownMenuItemButton<T>(
route: widget.route,
padding: widget.padding,
buttonRect: widget.buttonRect,
constraints: widget.constraints,
itemIndex: itemIndex,
enableFeedback: widget.enableFeedback,
scrollController: widget.scrollController,
mouseCursor: widget.mouseCursor,
),
];
return FadeTransition(
opacity: _fadeOpacity,
child: CustomPaint(
painter: _DropdownMenuPainter(
color: widget.dropdownColor ?? Theme.of(context).canvasColor,
elevation: route.elevation,
selectedIndex: route.selectedIndex,
resize: _resize,
borderRadius: widget.borderRadius,
// This offset is passed as a callback, not a value, because it must
// be retrieved at paint time (after layout), not at build time.
getSelectedItemOffset: () => route.getItemOffset(route.selectedIndex),
),
child: Semantics(
role: SemanticsRole.menu,
scopesRoute: true,
namesRoute: true,
explicitChildNodes: true,
label: localizations.popupMenuLabel,
child: ClipRRect(
borderRadius: widget.borderRadius ?? BorderRadius.zero,
clipBehavior: widget.borderRadius != null ? Clip.antiAlias : Clip.none,
child: Material(
type: MaterialType.transparency,
textStyle: route.style,
child: ScrollConfiguration(
// Dropdown menus should never overscroll or display an overscroll indicator.
// Scrollbars are built-in below.
// Platform must use Theme and ScrollPhysics must be Clamping.
behavior: ScrollConfiguration.of(context).copyWith(
scrollbars: false,
overscroll: false,
physics: const ClampingScrollPhysics(),
platform: Theme.of(context).platform,
),
child: PrimaryScrollController(
controller: widget.scrollController,
child: Scrollbar(
thumbVisibility: true,
child: ListView(
// Ensure this always inherits the PrimaryScrollController
primary: true,
padding: kMaterialListPadding,
shrinkWrap: true,
children: children,
),
),
),
),
),
),
),
),
);
}
}
class _DropdownMenuRouteLayout<T> extends SingleChildLayoutDelegate {
_DropdownMenuRouteLayout({
required this.buttonRect,
required this.route,
required this.textDirection,
this.menuWidth,
});
final Rect buttonRect;
final _DropdownRoute<T> route;
final TextDirection? textDirection;
final double? menuWidth;
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
// The maximum height of a simple menu should be one or more rows less than
// the view height. This ensures a tappable area outside of the simple menu
// with which to dismiss the menu.
// -- https://material.io/design/components/menus.html#usage
double maxHeight = math.max(0.0, constraints.maxHeight - 2 * _kMenuItemHeight);
if (route.menuMaxHeight != null && route.menuMaxHeight! <= maxHeight) {
maxHeight = route.menuMaxHeight!;
}
// The width of a menu should be at most the view width. This ensures that
// the menu does not extend past the left and right edges of the screen.
final double width = math.min(constraints.maxWidth, menuWidth ?? buttonRect.width);
return BoxConstraints(minWidth: width, maxWidth: width, maxHeight: maxHeight);
}
@override
Offset getPositionForChild(Size size, Size childSize) {
final _MenuLimits menuLimits = route.getMenuLimits(
buttonRect,
size.height,
route.selectedIndex,
);
assert(() {
final Rect container = Offset.zero & size;
if (container.intersect(buttonRect) == buttonRect) {
// If the button was entirely on-screen, then verify
// that the menu is also on-screen.
// If the button was a bit off-screen, then, oh well.
assert(menuLimits.top >= 0.0);
assert(menuLimits.top + menuLimits.height <= size.height);
}
return true;
}());
assert(textDirection != null);
final double left = switch (textDirection!) {
TextDirection.rtl => clampDouble(buttonRect.right, 0.0, size.width) - childSize.width,
TextDirection.ltr => clampDouble(buttonRect.left, 0.0, size.width - childSize.width),
};
return Offset(left, menuLimits.top);
}
@override
bool shouldRelayout(_DropdownMenuRouteLayout<T> oldDelegate) {
return buttonRect != oldDelegate.buttonRect || textDirection != oldDelegate.textDirection;
}
}
// We box the return value so that the return value can be null. Otherwise,
// canceling the route (which returns null) would get confused with actually
// returning a real null value.
@immutable
class _DropdownRouteResult<T> {
const _DropdownRouteResult(this.result);
final T? result;
@override
bool operator ==(Object other) {
return other is _DropdownRouteResult<T> && other.result == result;
}
@override
int get hashCode => result.hashCode;
}
class _MenuLimits {
const _MenuLimits(this.top, this.bottom, this.height, this.scrollOffset);
final double top;
final double bottom;
final double height;
final double scrollOffset;
}
class _DropdownRoute<T> extends PopupRoute<_DropdownRouteResult<T>> {
_DropdownRoute({
required this.items,
required this.padding,
required this.buttonRect,
required this.selectedIndex,
this.elevation = 8,
required this.capturedThemes,
required this.style,
this.barrierLabel,
this.itemHeight,
this.menuWidth,
this.dropdownColor,
this.menuMaxHeight,
required this.enableFeedback,
this.borderRadius,
this.barrierDismissible = true,
this.dropdownMenuItemMouseCursor,
}) : itemHeights = List<double>.filled(items.length, itemHeight ?? kMinInteractiveDimension);
final List<_MenuItem<T>> items;
final EdgeInsetsGeometry padding;
final Rect buttonRect;
final int selectedIndex;
final int elevation;
final CapturedThemes capturedThemes;
final TextStyle style;
final double? itemHeight;
final double? menuWidth;
final Color? dropdownColor;
final double? menuMaxHeight;
final bool enableFeedback;
final BorderRadius? borderRadius;
final MouseCursor? dropdownMenuItemMouseCursor;
final List<double> itemHeights;
@override
Duration get transitionDuration => _kDropdownMenuDuration;
@override
final bool barrierDismissible;
@override
Color? get barrierColor => null;
@override
final String? barrierLabel;
@override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return _DropdownRoutePage<T>(
route: this,
constraints: constraints,
items: items,
padding: padding,
buttonRect: buttonRect,
selectedIndex: selectedIndex,
elevation: elevation,
capturedThemes: capturedThemes,
style: style,
dropdownColor: dropdownColor,
enableFeedback: enableFeedback,
borderRadius: borderRadius,
menuWidth: menuWidth,
mouseCursor: dropdownMenuItemMouseCursor,
);
},
);
}
void _dismiss() {
if (isActive) {
navigator?.removeRoute(this);
}
}
double getItemOffset(int index) {
double offset = kMaterialListPadding.top;
if (items.isNotEmpty && index > 0) {
assert(items.length == itemHeights.length);
offset += itemHeights
.sublist(0, index)
.reduce((double total, double height) => total + height);
}
return offset;
}
// Returns the vertical extent of the menu and the initial scrollOffset
// for the ListView that contains the menu items. The vertical center of the
// selected item is aligned with the button's vertical center, as far as
// that's possible given availableHeight.
_MenuLimits getMenuLimits(Rect buttonRect, double availableHeight, int index) {
double computedMaxHeight = availableHeight - 2.0 * _kMenuItemHeight;
if (menuMaxHeight != null) {
computedMaxHeight = math.min(computedMaxHeight, menuMaxHeight!);
}
final double buttonTop = buttonRect.top;
final double buttonBottom = math.min(buttonRect.bottom, availableHeight);
final double selectedItemOffset = getItemOffset(index);
// If the button is placed on the bottom or top of the screen, its top or
// bottom may be less than [_kMenuItemHeight] from the edge of the screen.
// In this case, we want to change the menu limits to align with the top
// or bottom edge of the button.
final double topLimit = math.min(_kMenuItemHeight, buttonTop);
final double bottomLimit = math.max(availableHeight - _kMenuItemHeight, buttonBottom);
double menuTop =
(buttonTop - selectedItemOffset) - (itemHeights[selectedIndex] - buttonRect.height) / 2.0;
double preferredMenuHeight = kMaterialListPadding.vertical;
if (items.isNotEmpty) {
preferredMenuHeight += itemHeights.reduce((double total, double height) => total + height);
}
// If there are too many elements in the menu, we need to shrink it down
// so it is at most the computedMaxHeight.
final double menuHeight = math.min(computedMaxHeight, preferredMenuHeight);
double menuBottom = menuTop + menuHeight;
// If the computed top or bottom of the menu are outside of the range
// specified, we need to bring them into range. If the item height is larger
// than the button height and the button is at the very bottom or top of the
// screen, the menu will be aligned with the bottom or top of the button
// respectively.
if (menuTop < topLimit) {
menuTop = math.min(buttonTop, topLimit);
menuBottom = menuTop + menuHeight;
}
if (menuBottom > bottomLimit) {
menuBottom = math.max(buttonBottom, bottomLimit);
menuTop = menuBottom - menuHeight;
}
if (menuBottom - itemHeights[selectedIndex] / 2.0 < buttonBottom - buttonRect.height / 2.0) {
menuBottom = buttonBottom - buttonRect.height / 2.0 + itemHeights[selectedIndex] / 2.0;
menuTop = menuBottom - menuHeight;
}
double scrollOffset = 0;
// If all of the menu items will not fit within availableHeight then
// compute the scroll offset that will line the selected menu item up
// with the select item. This is only done when the menu is first
// shown - subsequently we leave the scroll offset where the user left
// it. This scroll offset is only accurate for fixed height menu items
// (the default).
if (preferredMenuHeight > computedMaxHeight) {
// The offset should be zero if the selected item is in view at the beginning
// of the menu. Otherwise, the scroll offset should center the item if possible.
scrollOffset = math.max(0.0, selectedItemOffset - (buttonTop - menuTop));
// If the selected item's scroll offset is greater than the maximum scroll offset,
// set it instead to the maximum allowed scroll offset.
scrollOffset = math.min(scrollOffset, preferredMenuHeight - menuHeight);
}
assert((menuBottom - menuTop - menuHeight).abs() < precisionErrorTolerance);
return _MenuLimits(menuTop, menuBottom, menuHeight, scrollOffset);
}
}
class _DropdownRoutePage<T> extends StatefulWidget {
const _DropdownRoutePage({
super.key,
required this.route,
required this.constraints,
this.items,
required this.padding,
required this.buttonRect,
required this.selectedIndex,
this.elevation = 8,
required this.capturedThemes,
this.style,
required this.dropdownColor,
required this.enableFeedback,
this.borderRadius,
this.menuWidth,
this.mouseCursor,
});
final _DropdownRoute<T> route;
final BoxConstraints constraints;
final List<_MenuItem<T>>? items;
final EdgeInsetsGeometry padding;
final Rect buttonRect;
final int selectedIndex;
final int elevation;
final CapturedThemes capturedThemes;
final TextStyle? style;
final Color? dropdownColor;
final bool enableFeedback;
final BorderRadius? borderRadius;
final double? menuWidth;
final MouseCursor? mouseCursor;
@override
State<_DropdownRoutePage<T>> createState() => _DropdownRoutePageState<T>();
}
class _DropdownRoutePageState<T> extends State<_DropdownRoutePage<T>> {
late ScrollController _scrollController;
@override
void initState() {
super.initState();
// Computing the initialScrollOffset now, before the items have been laid
// out. This only works if the item heights are effectively fixed, i.e. either
// DropdownButton.itemHeight is specified or DropdownButton.itemHeight is null
// and all of the items' intrinsic heights are less than kMinInteractiveDimension.
// Otherwise the initialScrollOffset is just a rough approximation based on
// treating the items as if their heights were all equal to kMinInteractiveDimension.
final _MenuLimits menuLimits = widget.route.getMenuLimits(
widget.buttonRect,
widget.constraints.maxHeight,
widget.selectedIndex,
);
_scrollController = ScrollController(initialScrollOffset: menuLimits.scrollOffset);
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasDirectionality(context));
final TextDirection? textDirection = Directionality.maybeOf(context);
final Widget menu = _DropdownMenu<T>(
route: widget.route,
padding: widget.padding.resolve(textDirection),
buttonRect: widget.buttonRect,
constraints: widget.constraints,
dropdownColor: widget.dropdownColor,
enableFeedback: widget.enableFeedback,
borderRadius: widget.borderRadius,
scrollController: _scrollController,
mouseCursor: widget.mouseCursor,
);
return MediaQuery.removePadding(
context: context,
removeTop: true,
removeBottom: true,
removeLeft: true,
removeRight: true,
child: Builder(
builder: (BuildContext context) {
return CustomSingleChildLayout(
delegate: _DropdownMenuRouteLayout<T>(
buttonRect: widget.buttonRect,
route: widget.route,
textDirection: textDirection,
menuWidth: widget.menuWidth,
),
child: widget.capturedThemes.wrap(menu),
);
},
),
);
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
}
// This widget enables _DropdownRoute to look up the sizes of
// each menu item. These sizes are used to compute the offset of the selected
// item so that _DropdownRoutePage can align the vertical center of the
// selected item lines up with the vertical center of the dropdown button,
// as closely as possible.
class _MenuItem<T> extends SingleChildRenderObjectWidget {
const _MenuItem({super.key, required this.onLayout, required this.item}) : super(child: item);
final ValueChanged<Size> onLayout;
final DropdownMenuItem<T>? item;
@override
RenderObject createRenderObject(BuildContext context) {
return _RenderMenuItem(onLayout);
}
@override
void updateRenderObject(BuildContext context, covariant _RenderMenuItem renderObject) {
renderObject.onLayout = onLayout;
}
}
class _RenderMenuItem extends RenderProxyBox {
_RenderMenuItem(this.onLayout, [RenderBox? child]) : super(child);
ValueChanged<Size> onLayout;
@override
void performLayout() {
super.performLayout();
onLayout(size);
}
}
// The container widget for a menu item created by a [DropdownButton]. It
// provides the default configuration for [DropdownMenuItem]s, as well as a
// [DropdownButton]'s hint and disabledHint widgets.
class _DropdownMenuItemContainer extends StatelessWidget {
/// Creates an item for a dropdown menu.
///
/// The [child] argument is required.
const _DropdownMenuItemContainer({
super.key,
this.alignment = AlignmentDirectional.centerStart,
required this.child,
});
/// The widget below this widget in the tree.
///
/// Typically a [Text] widget.
final Widget child;
/// Defines how the item is positioned within the container.
///
/// Defaults to [AlignmentDirectional.centerStart].
///
/// See also:
///
/// * [Alignment], a class with convenient constants typically used to
/// specify an [AlignmentGeometry].
/// * [AlignmentDirectional], like [Alignment] for specifying alignments
/// relative to text direction.
final AlignmentGeometry alignment;
@override
Widget build(BuildContext context) {
return Semantics(
button: true,
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: _kMenuItemHeight),
child: Align(alignment: alignment, child: child),
),
);
}
}
/// An item in a menu created by a [DropdownButton].
///
/// The type `T` is the type of the value the entry represents. All the entries
/// in a given menu must represent values with consistent types.
class DropdownMenuItem<T> extends _DropdownMenuItemContainer {
/// Creates an item for a dropdown menu.
///
/// The [child] argument is required.
const DropdownMenuItem({
super.key,
this.onTap,
this.value,
this.enabled = true,
super.alignment,
required super.child,
});
/// Called when the dropdown menu item is tapped.
final VoidCallback? onTap;
/// The value to return if the user selects this menu item.
///
/// Eventually returned in a call to [DropdownButton.onChanged].
final T? value;
/// Whether or not a user can select this menu item.
///
/// Defaults to `true`.
final bool enabled;
}
/// An inherited widget that causes any descendant [DropdownButton]
/// widgets to not include their regular underline.
///
/// This is used by [DataTable] to remove the underline from any
/// [DropdownButton] widgets placed within material data tables, as
/// required by the Material Design specification.
class DropdownButtonHideUnderline extends InheritedWidget {
/// Creates a [DropdownButtonHideUnderline]. A non-null [child] must
/// be given.
const DropdownButtonHideUnderline({super.key, required super.child});
/// Returns whether the underline of [DropdownButton] widgets should
/// be hidden.
static bool at(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<DropdownButtonHideUnderline>() != null;
}
@override
bool updateShouldNotify(DropdownButtonHideUnderline oldWidget) => false;
}
/// A Material Design button for selecting from a list of items.
///
/// A dropdown button lets the user select from a number of items. The button
/// shows the currently selected item as well as an arrow that opens a menu for
/// selecting another item.
///
/// ## Updating to [DropdownMenu]
///
/// There is a Material 3 version of this component,
/// [DropdownMenu] that is preferred for applications that are configured
/// for Material 3 (see [ThemeData.useMaterial3]).
/// The [DropdownMenu] widget's visuals
/// are a little bit different, see the Material 3 spec at
/// <https://m3.material.io/components/menus/guidelines> for
/// more details.
///
/// The [DropdownMenu] widget's API is also slightly different.
/// To update from [DropdownButton] to [DropdownMenu], you will
/// need to make the following changes:
///
/// 1. Instead of using [DropdownButton.items], which
/// takes a list of [DropdownMenuItem]s, use
/// [DropdownMenu.dropdownMenuEntries], which
/// takes a list of [DropdownMenuEntry]'s.
///
/// 2. Instead of using [DropdownButton.onChanged],
/// use [DropdownMenu.onSelected], which is also
/// a callback that is called when the user selects an entry.
///
/// 3. In [DropdownMenu] it is not required to track
/// the current selection in your app's state.
/// So, instead of tracking the current selection in
/// the [DropdownButton.value] property, you can set the
/// [DropdownMenu.initialSelection] property to the
/// item that should be selected before there is any user action.
///
/// 4. You may also need to make changes to the styling of the
/// [DropdownMenu], see the properties in the [DropdownMenu]
/// constructor for more details.
///
/// See the sample below for an example of migrating
/// from [DropdownButton] to [DropdownMenu].
///
/// ## Using [DropdownButton]
/// {@youtube 560 315 https://www.youtube.com/watch?v=ZzQ_PWrFihg}
///
/// One ancestor must be a [Material] widget and typically this is
/// provided by the app's [Scaffold].
///
/// The type `T` is the type of the [value] that each dropdown item represents.
/// All the entries in a given menu must represent values with consistent types.
/// Typically, an enum is used. Each [DropdownMenuItem] in [items] must be
/// specialized with that same type argument.
///
/// The [onChanged] callback should update a state variable that defines the
/// dropdown's value. It should also call [State.setState] to rebuild the
/// dropdown with the new value.
///
///
/// {@tool dartpad}
/// This sample shows a [DropdownButton] with a large arrow icon,
/// purple text style, and bold purple underline, whose value is one of "One",
/// "Two", "Three", or "Four".
///
/// 
///
/// ** See code in examples/api/lib/material/dropdown/dropdown_button.0.dart **
/// {@end-tool}
///
/// If the [onChanged] callback is null or the list of [items] is null
/// then the dropdown button will be disabled, i.e. its arrow will be
/// displayed in grey and it will not respond to input. A disabled button
/// will display the [disabledHint] widget if it is non-null. However, if
/// [disabledHint] is null and [hint] is non-null, the [hint] widget will
/// instead be displayed.
///
/// {@tool dartpad}
/// This sample shows how you would rewrite the above [DropdownButton]
/// to use the [DropdownMenu].
///
/// ** See code in examples/api/lib/material/dropdown_menu/dropdown_menu.1.dart **
/// {@end-tool}
///
///
/// See also:
///
/// * [DropdownButtonFormField], which integrates with the [Form] widget.
/// * [DropdownMenuItem], the class used to represent the [items].
/// * [DropdownButtonHideUnderline], which prevents its descendant dropdown buttons
/// from displaying their underlines.
/// * [ElevatedButton], [TextButton], ordinary buttons that trigger a single action.
/// * <https://material.io/design/components/menus.html#dropdown-menu>
class DropdownButton<T> extends StatefulWidget {
/// Creates a dropdown button.
///
/// The [items] must have distinct values. If [value] isn't null then it
/// must be equal to one of the [DropdownMenuItem] values. If [items] or
/// [onChanged] is null, the button will be disabled, the down arrow
/// will be greyed out.
///
/// If [value] is null and the button is enabled, [hint] will be displayed
/// if it is non-null.
///
/// If [value] is null and the button is disabled, [disabledHint] will be displayed
/// if it is non-null. If [disabledHint] is null, then [hint] will be displayed
/// if it is non-null.
///
/// The [dropdownColor] argument specifies the background color of the
/// dropdown when it is open. If it is null, the current theme's
/// [ThemeData.canvasColor] will be used instead.
DropdownButton({
super.key,
required this.items,
this.selectedItemBuilder,
this.value,
this.hint,
this.disabledHint,
required this.onChanged,