Flutter带下拉建议列表的搜索框

基于DropdownMenu实现

Flutter自带的DropdownMenu无法满足需求,在源码的基础上copy一份出来修改:

suggest_search_bar.dart:

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
import 'dart:async';

import 'package:flutter/material.dart';

class SuggestSearchBar extends StatefulWidget {
/// 带建议的搜索框
const SuggestSearchBar({
super.key,
this.width,
this.maxSuggestHeight = 300,
this.hintText,
this.onSelected,
this.buildSuggestion,
this.inputController,
this.defaultSuggestion,
this.trailingIcon,
this.isCollapsed = false,
this.contentPadding,
});

/// 搜索框的宽度,只有当`trailingIcon`不为null时生效
final double? width;

/// 建议栏的最大高度
final double maxSuggestHeight;

final String? hintText;
final void Function(String?)? onSelected;
final TextEditingController? inputController;
final List<String>? defaultSuggestion;
final Widget? trailingIcon;

/// 构建搜索建议
///
/// 传入一个带`String`参数的方法,该参数为当前搜索框输入的值
/// 返回一个`Future<List<String>>`,为建议值列表
final Future<List<String>> Function(String)? buildSuggestion;

/// 即搜索框[TextField]的[isCollapsed]
final bool isCollapsed;

/// 即搜索框[TextField]的[contentPadding]
final EdgeInsetsGeometry? contentPadding;

@override
State<SuggestSearchBar> createState() => _SuggestSearchBarState();
}

class _SuggestSearchBarState extends State<SuggestSearchBar> {
final StreamController<List<String>> streamController = StreamController();

late TextEditingController _inputController;
@override
void initState() {
super.initState();
_inputController = widget.inputController ?? TextEditingController();
if (widget.inputController == null || widget.buildSuggestion == null) {
return;
}
widget.inputController!.addListener(onChanged);
}

onChanged() async {
List<String> suggestionList =
await widget.buildSuggestion!.call(widget.inputController!.text);
streamController.add(suggestionList);
}

@override
Widget build(BuildContext context) {
return StreamBuilder<List<String>>(
stream: streamController.stream,
initialData: widget.defaultSuggestion,
builder: (context, snapshot) {
List<DropdownMenuEntry<String>> entryList = [];
if (snapshot.data != null) {
entryList = snapshot.data!
.map((e) => DropdownMenuEntry<String>(label: e, value: e))
.toList();
}
return CustomedDropdownMenu<String>(
width: widget.width,
menuHeight: widget.maxSuggestHeight,
hintText: widget.hintText,
trailingIcon: widget.trailingIcon ??
InkWell(
onTap: () {
_inputController.text = "";
widget.onSelected?.call("");
},
child: Icon(Icons.search)),
onSelected: widget.onSelected,
controller: _inputController,
dropdownMenuEntries: entryList,
enableFilter: true,
requestFocusOnTap: true,
isCollapsed: widget.isCollapsed,
contentPadding: widget.contentPadding,
);
},
);
}
}

对源码的修改:

customed_dropdown_menu.dart:

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
// 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.

import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';

// Navigation shortcuts to move the selected menu items up or down.
Map<ShortcutActivator, Intent> _kMenuTraversalShortcuts =
<ShortcutActivator, Intent>{
LogicalKeySet(LogicalKeyboardKey.arrowUp): const _ArrowUpIntent(),
LogicalKeySet(LogicalKeyboardKey.arrowDown): const _ArrowDownIntent(),
};

const double _kMinimumWidth = 112.0;

const double _kDefaultHorizontalPadding = 12.0;

/// A dropdown menu that can be opened from a [TextField]. The selected
/// menu item is displayed in that field.
///
/// This widget is used to help people make a choice from a menu and put the
/// selected item into the text input field. People can also filter the list based
/// on the text input or search one item in the menu list.
///
/// The menu is composed of a list of [DropdownMenuEntry]s. People can provide information,
/// such as: label, leading icon or trailing icon for each entry. The [TextField]
/// will be updated based on the selection from the menu entries. The text field
/// will stay empty if the selected entry is disabled.
///
/// The dropdown menu can be traversed by pressing the up or down key. During the
/// process, the corresponding item will be highlighted and the text field will be updated.
/// Disabled items will be skipped during traversal.
///
/// The menu can be scrollable if not all items in the list are displayed at once.
///
/// {@tool dartpad}
/// This sample shows how to display outlined [DropdownMenu] and filled [DropdownMenu].
///
/// ** See code in examples/api/lib/material/dropdown_menu/dropdown_menu.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [MenuAnchor], which is a widget used to mark the "anchor" for a set of submenus.
/// The [DropdownMenu] uses a [TextField] as the "anchor".
/// * [TextField], which is a text input widget that uses an [InputDecoration].
/// * [DropdownMenuEntry], which is used to build the [MenuItemButton] in the [DropdownMenu] list.
class CustomedDropdownMenu<T> extends StatefulWidget {
/// Creates a const [DropdownMenu].
///
/// The leading and trailing icons in the text field can be customized by using
/// [leadingIcon], [trailingIcon] and [selectedTrailingIcon] properties. They are
/// passed down to the [InputDecoration] properties, and will override values
/// in the [InputDecoration.prefixIcon] and [InputDecoration.suffixIcon].
///
/// Except leading and trailing icons, the text field can be configured by the
/// [InputDecorationTheme] property. The menu can be configured by the [menuStyle].
const CustomedDropdownMenu({
super.key,
this.enabled = true,
this.width,
this.menuHeight,
this.leadingIcon,
this.trailingIcon,
this.label,
this.hintText,
this.helperText,
this.errorText,
this.selectedTrailingIcon,
this.enableFilter = false,
this.enableSearch = true,
this.textStyle,
this.inputDecorationTheme,
this.menuStyle,
this.controller,
this.initialSelection,
this.onSelected,
this.requestFocusOnTap,
required this.dropdownMenuEntries,
this.isCollapsed = false,
this.contentPadding,
});

/// Determine if the [DropdownMenu] is enabled.
///
/// Defaults to true.
final bool enabled;

/// Determine the width of the [DropdownMenu].
///
/// If this is null, the width of the [DropdownMenu] will be the same as the width of the widest
/// menu item plus the width of the leading/trailing icon.
final double? width;

/// Determine the height of the menu.
///
/// If this is null, the menu will display as many items as possible on the screen.
final double? menuHeight;

/// An optional Icon at the front of the text input field.
///
/// Defaults to null. If this is not null, the menu items will have extra paddings to be aligned
/// with the text in the text field.
final Widget? leadingIcon;

/// An optional icon at the end of the text field.
///
/// Defaults to an [Icon] with [Icons.arrow_drop_down].
final Widget? trailingIcon;

/// Optional widget that describes the input field.
///
/// When the input field is empty and unfocused, the label is displayed on
/// top of the input field (i.e., at the same location on the screen where
/// text may be entered in the input field). When the input field receives
/// focus (or if the field is non-empty), the label moves above, either
/// vertically adjacent to, or to the center of the input field.
///
/// Defaults to null.
final Widget? label;

/// Text that suggests what sort of input the field accepts.
///
/// Defaults to null;
final String? hintText;

/// Text that provides context about the [DropdownMenu]'s value, such
/// as how the value will be used.
///
/// If non-null, the text is displayed below the input field, in
/// the same location as [errorText]. If a non-null [errorText] value is
/// specified then the helper text is not shown.
///
/// Defaults to null;
///
/// See also:
///
/// * [InputDecoration.helperText], which is the text that provides context about the [InputDecorator.child]'s value.
final String? helperText;

/// Text that appears below the input field and the border to show the error message.
///
/// If non-null, the border's color animates to red and the [helperText] is not shown.
///
/// Defaults to null;
///
/// See also:
///
/// * [InputDecoration.errorText], which is the text that appears below the [InputDecorator.child] and the border.
final String? errorText;

/// An optional icon at the end of the text field to indicate that the text
/// field is pressed.
///
/// Defaults to an [Icon] with [Icons.arrow_drop_up].
final Widget? selectedTrailingIcon;

/// Determine if the menu list can be filtered by the text input.
///
/// Defaults to false.
final bool enableFilter;

/// Determine if the first item that matches the text input can be highlighted.
///
/// Defaults to true as the search function could be commonly used.
final bool enableSearch;

/// The text style for the [TextField] of the [DropdownMenu];
///
/// Defaults to the overall theme's [TextTheme.labelLarge]
/// if the dropdown menu theme's value is null.
final TextStyle? textStyle;

/// Defines the default appearance of [InputDecoration] to show around the text field.
///
/// By default, shows a outlined text field.
final InputDecorationTheme? inputDecorationTheme;

/// The [MenuStyle] that defines the visual attributes of the menu.
///
/// The default width of the menu is set to the width of the text field.
final MenuStyle? menuStyle;

/// Controls the text being edited or selected in the menu.
///
/// If null, this widget will create its own [TextEditingController].
final TextEditingController? controller;

/// The value used to for an initial selection.
///
/// Defaults to null.
final T? initialSelection;

/// The callback is called when a selection is made.
///
/// Defaults to null. If null, only the text field is updated.
final ValueChanged<T?>? onSelected;

/// Determine if the dropdown button requests focus and the on-screen virtual
/// keyboard is shown in response to a touch event.
///
/// By default, on mobile platforms, tapping on the text field and opening
/// the menu will not cause a focus request and the virtual keyboard will not
/// appear. The default behavior for desktop platforms is for the dropdown to
/// take the focus.
///
/// Defaults to null. Setting this field to true or false, rather than allowing
/// the implementation to choose based on the platform, can be useful for
/// applications that want to override the default behavior.
final bool? requestFocusOnTap;

/// Descriptions of the menu items in the [DropdownMenu].
///
/// This is a required parameter. It is recommended that at least one [DropdownMenuEntry]
/// is provided. If this is an empty list, the menu will be empty and only
/// contain space for padding.
final List<DropdownMenuEntry<T>> dropdownMenuEntries;

/// 即搜索框[TextField]的[isCollapsed]
final bool isCollapsed;

/// 即搜索框[TextField]的[contentPadding]
final EdgeInsetsGeometry? contentPadding;

@override
State<CustomedDropdownMenu<T>> createState() =>
_CustomedDropdownMenuState<T>();
}

class _CustomedDropdownMenuState<T> extends State<CustomedDropdownMenu<T>> {
final GlobalKey _anchorKey = GlobalKey();
final GlobalKey _leadingKey = GlobalKey();
final MenuController _controller = MenuController();
late final TextEditingController _textEditingController;
late bool _enableFilter;
late List<DropdownMenuEntry<T>> filteredEntries;
List<Widget>? _initialMenu;
int? currentHighlight;
double? leadingPadding;
bool _menuHasEnabledItem = false;

@override
void initState() {
super.initState();
_textEditingController = widget.controller ?? TextEditingController();
_enableFilter = widget.enableFilter;
filteredEntries = widget.dropdownMenuEntries;
_menuHasEnabledItem =
filteredEntries.any((DropdownMenuEntry<T> entry) => entry.enabled);

final int index = filteredEntries.indexWhere(
(DropdownMenuEntry<T> entry) => entry.value == widget.initialSelection);
if (index != -1) {
_textEditingController.text = filteredEntries[index].label;
_textEditingController.selection =
TextSelection.collapsed(offset: _textEditingController.text.length);
}
refreshLeadingPadding();
}

@override
void didUpdateWidget(CustomedDropdownMenu<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.dropdownMenuEntries != widget.dropdownMenuEntries) {
_menuHasEnabledItem =
filteredEntries.any((DropdownMenuEntry<T> entry) => entry.enabled);
}
if (oldWidget.leadingIcon != widget.leadingIcon) {
refreshLeadingPadding();
}
if (oldWidget.initialSelection != widget.initialSelection) {
final int index = filteredEntries.indexWhere(
(DropdownMenuEntry<T> entry) =>
entry.value == widget.initialSelection);
if (index != -1) {
_textEditingController.text = filteredEntries[index].label;
_textEditingController.selection =
TextSelection.collapsed(offset: _textEditingController.text.length);
}
}
}

bool canRequestFocus() {
if (widget.requestFocusOnTap != null) {
return widget.requestFocusOnTap!;
}

switch (Theme.of(context).platform) {
case TargetPlatform.iOS:
case TargetPlatform.android:
case TargetPlatform.fuchsia:
return false;
case TargetPlatform.macOS:
case TargetPlatform.linux:
case TargetPlatform.windows:
return true;
}
}

void refreshLeadingPadding() {
WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() {
leadingPadding = getWidth(_leadingKey);
});
});
}

double? getWidth(GlobalKey key) {
final BuildContext? context = key.currentContext;
if (context != null) {
final RenderBox box = context.findRenderObject()! as RenderBox;
return box.size.width;
}
return null;
}

List<DropdownMenuEntry<T>> filter(List<DropdownMenuEntry<T>> entries,
TextEditingController textEditingController) {
final String filterText = textEditingController.text.toLowerCase();
return entries
.where((DropdownMenuEntry<T> entry) =>
entry.label.toLowerCase().contains(filterText))
.toList();
}

int? search(List<DropdownMenuEntry<T>> entries,
TextEditingController textEditingController) {
final String searchText = textEditingController.value.text.toLowerCase();
if (searchText.isEmpty) {
return null;
}
final int index = entries.indexWhere((DropdownMenuEntry<T> entry) =>
entry.label.toLowerCase().contains(searchText));

return index != -1 ? index : null;
}

List<Widget> _buildButtons(List<DropdownMenuEntry<T>> filteredEntries,
TextEditingController textEditingController, TextDirection textDirection,
{int? focusedIndex}) {
final List<Widget> result = <Widget>[];
final double padding = leadingPadding ?? _kDefaultHorizontalPadding;
final ButtonStyle defaultStyle;
switch (textDirection) {
case TextDirection.rtl:
defaultStyle = MenuItemButton.styleFrom(
padding:
EdgeInsets.only(left: _kDefaultHorizontalPadding, right: padding),
);
break;
case TextDirection.ltr:
defaultStyle = MenuItemButton.styleFrom(
padding:
EdgeInsets.only(left: padding, right: _kDefaultHorizontalPadding),
);
}

for (int i = 0; i < filteredEntries.length; i++) {
final DropdownMenuEntry<T> entry = filteredEntries[i];
ButtonStyle effectiveStyle = entry.style ?? defaultStyle;
final Color focusedBackgroundColor = effectiveStyle.foregroundColor
?.resolve(<MaterialState>{MaterialState.focused}) ??
Theme.of(context).colorScheme.onSurface;

// Simulate the focused state because the text field should always be focused
// during traversal. If the menu item has a custom foreground color, the "focused"
// color will also change to foregroundColor.withOpacity(0.12).
effectiveStyle = entry.enabled && i == focusedIndex
? effectiveStyle.copyWith(
backgroundColor: MaterialStatePropertyAll<Color>(
focusedBackgroundColor.withOpacity(0.12)))
: effectiveStyle;

final MenuItemButton menuItemButton = MenuItemButton(
style: effectiveStyle,
leadingIcon: entry.leadingIcon,
trailingIcon: entry.trailingIcon,
onPressed: entry.enabled
? () {
textEditingController.text = entry.label;
textEditingController.selection = TextSelection.collapsed(
offset: textEditingController.text.length);
currentHighlight = widget.enableSearch ? i : null;
widget.onSelected?.call(entry.value);
}
: null,
requestFocusOnHover: false,
child: Text(entry.label),
);
result.add(menuItemButton);
}

return result;
}

void handleUpKeyInvoke(_) => setState(() {
if (!_menuHasEnabledItem || !_controller.isOpen) {
return;
}
_enableFilter = false;
currentHighlight ??= 0;
currentHighlight = (currentHighlight! - 1) % filteredEntries.length;
while (!filteredEntries[currentHighlight!].enabled) {
currentHighlight = (currentHighlight! - 1) % filteredEntries.length;
}
final String currentLabel = filteredEntries[currentHighlight!].label;
_textEditingController.text = currentLabel;
_textEditingController.selection =
TextSelection.collapsed(offset: _textEditingController.text.length);
});

void handleDownKeyInvoke(_) => setState(() {
if (!_menuHasEnabledItem || !_controller.isOpen) {
return;
}
_enableFilter = false;
currentHighlight ??= -1;
currentHighlight = (currentHighlight! + 1) % filteredEntries.length;
while (!filteredEntries[currentHighlight!].enabled) {
currentHighlight = (currentHighlight! + 1) % filteredEntries.length;
}
final String currentLabel = filteredEntries[currentHighlight!].label;
_textEditingController.text = currentLabel;
_textEditingController.selection =
TextSelection.collapsed(offset: _textEditingController.text.length);
});

void handlePressed(MenuController controller) {
if (controller.isOpen) {
currentHighlight = null;
controller.close();
} else {
// close to open
if (_textEditingController.text.isNotEmpty) {
_enableFilter = false;
}
controller.open();
}
setState(() {});
}

@override
void dispose() {
super.dispose();
}

@override
Widget build(BuildContext context) {
final TextDirection textDirection = Directionality.of(context);
_initialMenu ??= _buildButtons(
widget.dropdownMenuEntries, _textEditingController, textDirection);
final DropdownMenuThemeData theme = DropdownMenuTheme.of(context);
final DropdownMenuThemeData defaults = _DropdownMenuDefaultsM3(context);

if (_enableFilter) {
filteredEntries =
filter(widget.dropdownMenuEntries, _textEditingController);
}

if (widget.enableSearch) {
currentHighlight = search(filteredEntries, _textEditingController);
}

final List<Widget> menu = _buildButtons(
filteredEntries, _textEditingController, textDirection,
focusedIndex: currentHighlight);

final TextStyle? effectiveTextStyle =
widget.textStyle ?? theme.textStyle ?? defaults.textStyle;

MenuStyle? effectiveMenuStyle =
widget.menuStyle ?? theme.menuStyle ?? defaults.menuStyle!;

final double? anchorWidth = getWidth(_anchorKey);
if (widget.width != null) {
effectiveMenuStyle = effectiveMenuStyle.copyWith(
minimumSize:
MaterialStatePropertyAll<Size?>(Size(widget.width!, 0.0)));
} else if (anchorWidth != null) {
effectiveMenuStyle = effectiveMenuStyle.copyWith(
minimumSize: MaterialStatePropertyAll<Size?>(Size(anchorWidth, 0.0)));
}

if (widget.menuHeight != null) {
effectiveMenuStyle = effectiveMenuStyle.copyWith(
maximumSize: MaterialStatePropertyAll<Size>(
Size(double.infinity, widget.menuHeight!)));
}
final InputDecorationTheme effectiveInputDecorationTheme =
widget.inputDecorationTheme ??
theme.inputDecorationTheme ??
defaults.inputDecorationTheme!;

final MouseCursor effectiveMouseCursor =
canRequestFocus() ? SystemMouseCursors.text : SystemMouseCursors.click;

return Shortcuts(
shortcuts: _kMenuTraversalShortcuts,
child: Actions(
actions: <Type, Action<Intent>>{
_ArrowUpIntent: CallbackAction<_ArrowUpIntent>(
onInvoke: handleUpKeyInvoke,
),
_ArrowDownIntent: CallbackAction<_ArrowDownIntent>(
onInvoke: handleDownKeyInvoke,
),
},
child: MenuAnchor(
style: effectiveMenuStyle,
controller: _controller,
menuChildren: menu,
crossAxisUnconstrained: false, // 将建议设置为与搜索框宽度相同
onClose: () {
// setState(() {});
}, // To update the status of the IconButton

// 搜索框布局
builder:
(BuildContext context, MenuController controller, Widget? child) {
assert(_initialMenu != null);
final Widget? trailingButton;
if (widget.trailingIcon != null) {
trailingButton = Padding(
padding: const EdgeInsets.all(4.0),
child: IconButton(
isSelected: controller.isOpen,
icon:
widget.trailingIcon ?? const Icon(Icons.arrow_drop_down),
selectedIcon: widget.selectedTrailingIcon ??
const Icon(Icons.arrow_drop_up),
onPressed: () {
handlePressed(controller);
},
),
);
} else {
trailingButton = null;
}

final Widget leadingButton = Padding(
padding: const EdgeInsets.all(8.0),
child: widget.leadingIcon ?? const SizedBox());

return _DropdownMenuBody(
width: widget.width,
children: <Widget>[
TextField(
key: _anchorKey,
mouseCursor: effectiveMouseCursor,
canRequestFocus: canRequestFocus(),
enableInteractiveSelection: canRequestFocus(),
textAlignVertical: TextAlignVertical.center,
style: effectiveTextStyle,
controller: _textEditingController,
onEditingComplete: () {
if (currentHighlight != null) {
final DropdownMenuEntry<T> entry =
filteredEntries[currentHighlight!];
if (entry.enabled) {
_textEditingController.text = entry.label;
_textEditingController.selection =
TextSelection.collapsed(
offset: _textEditingController.text.length);
widget.onSelected?.call(entry.value);
}
} else {
widget.onSelected?.call(null);
}
if (!widget.enableSearch) {
currentHighlight = null;
}
if (_textEditingController.text.isNotEmpty) {
controller.close();
}
},
onTap: () {
handlePressed(controller);
},
onChanged: (String text) {
controller.open();
setState(() {
filteredEntries = widget.dropdownMenuEntries;
_enableFilter = widget.enableFilter;
});
},
decoration: InputDecoration(
enabled: widget.enabled,
label: widget.label,
hintText: widget.hintText,
helperText: widget.helperText,
errorText: widget.errorText,
contentPadding: widget.contentPadding,
isCollapsed: widget.isCollapsed,
prefixIcon: widget.leadingIcon != null
? Container(
key: _leadingKey, child: widget.leadingIcon)
: null,
suffixIcon: trailingButton,
).applyDefaults(effectiveInputDecorationTheme)),
for (Widget c in _initialMenu!) c,
if (trailingButton != null) trailingButton,
leadingButton,
],
);
},
),
),
);
}
}

class _ArrowUpIntent extends Intent {
const _ArrowUpIntent();
}

class _ArrowDownIntent extends Intent {
const _ArrowDownIntent();
}

class _DropdownMenuBody extends MultiChildRenderObjectWidget {
const _DropdownMenuBody({
super.children,
this.width,
});

final double? width;

@override
_RenderDropdownMenuBody createRenderObject(BuildContext context) {
return _RenderDropdownMenuBody(
width: width,
);
}
}

class _DropdownMenuBodyParentData extends ContainerBoxParentData<RenderBox> {}

class _RenderDropdownMenuBody extends RenderBox
with
ContainerRenderObjectMixin<RenderBox, _DropdownMenuBodyParentData>,
RenderBoxContainerDefaultsMixin<RenderBox,
_DropdownMenuBodyParentData> {
_RenderDropdownMenuBody({
this.width,
});

final double? width;

@override
void setupParentData(RenderBox child) {
if (child.parentData is! _DropdownMenuBodyParentData) {
child.parentData = _DropdownMenuBodyParentData();
}
}

@override
void performLayout() {
final BoxConstraints constraints = this.constraints;
double maxWidth = 0.0;
double? maxHeight;
RenderBox? child = firstChild;

final BoxConstraints innerConstraints = BoxConstraints(
maxWidth: width ?? computeMaxIntrinsicWidth(constraints.maxWidth),
maxHeight: computeMaxIntrinsicHeight(constraints.maxHeight),
);
while (child != null) {
if (child == firstChild) {
child.layout(innerConstraints, parentUsesSize: true);
maxHeight ??= child.size.height;
final _DropdownMenuBodyParentData childParentData =
child.parentData! as _DropdownMenuBodyParentData;
assert(child.parentData == childParentData);
child = childParentData.nextSibling;
continue;
}
child.layout(innerConstraints, parentUsesSize: true);
final _DropdownMenuBodyParentData childParentData =
child.parentData! as _DropdownMenuBodyParentData;
childParentData.offset = Offset.zero;
maxWidth = math.max(maxWidth, child.size.width);
maxHeight ??= child.size.height;
assert(child.parentData == childParentData);
child = childParentData.nextSibling;
}

assert(maxHeight != null);
maxWidth = math.max(_kMinimumWidth, maxWidth);
size = constraints.constrain(Size(width ?? maxWidth, maxHeight!));
}

@override
void paint(PaintingContext context, Offset offset) {
final RenderBox? child = firstChild;
if (child != null) {
final _DropdownMenuBodyParentData childParentData =
child.parentData! as _DropdownMenuBodyParentData;
context.paintChild(child, offset + childParentData.offset);
}
}

@override
Size computeDryLayout(BoxConstraints constraints) {
final BoxConstraints constraints = this.constraints;
double maxWidth = 0.0;
double? maxHeight;
RenderBox? child = firstChild;
final BoxConstraints innerConstraints = BoxConstraints(
maxWidth: width ?? computeMaxIntrinsicWidth(constraints.maxWidth),
maxHeight: computeMaxIntrinsicHeight(constraints.maxHeight),
);

while (child != null) {
if (child == firstChild) {
final Size childSize = child.getDryLayout(innerConstraints);
maxHeight ??= childSize.height;
final _DropdownMenuBodyParentData childParentData =
child.parentData! as _DropdownMenuBodyParentData;
assert(child.parentData == childParentData);
child = childParentData.nextSibling;
continue;
}
final Size childSize = child.getDryLayout(innerConstraints);
final _DropdownMenuBodyParentData childParentData =
child.parentData! as _DropdownMenuBodyParentData;
childParentData.offset = Offset.zero;
maxWidth = math.max(maxWidth, childSize.width);
maxHeight ??= childSize.height;
assert(child.parentData == childParentData);
child = childParentData.nextSibling;
}

assert(maxHeight != null);
maxWidth = math.max(_kMinimumWidth, maxWidth);
return constraints.constrain(Size(width ?? maxWidth, maxHeight!));
}

@override
double computeMinIntrinsicWidth(double height) {
RenderBox? child = firstChild;
double width = 0;
while (child != null) {
if (child == firstChild) {
final _DropdownMenuBodyParentData childParentData =
child.parentData! as _DropdownMenuBodyParentData;
child = childParentData.nextSibling;
continue;
}
final double maxIntrinsicWidth = child.getMinIntrinsicWidth(height);
if (child == lastChild) {
width += maxIntrinsicWidth;
}
if (child == childBefore(lastChild!)) {
width += maxIntrinsicWidth;
}
width = math.max(width, maxIntrinsicWidth);
final _DropdownMenuBodyParentData childParentData =
child.parentData! as _DropdownMenuBodyParentData;
child = childParentData.nextSibling;
}

return math.max(width, _kMinimumWidth);
}

@override
double computeMaxIntrinsicWidth(double height) {
RenderBox? child = firstChild;
double width = 0;
while (child != null) {
if (child == firstChild) {
final _DropdownMenuBodyParentData childParentData =
child.parentData! as _DropdownMenuBodyParentData;
child = childParentData.nextSibling;
continue;
}
final double maxIntrinsicWidth = child.getMaxIntrinsicWidth(height);
// Add the width of leading Icon.
if (child == lastChild) {
width += maxIntrinsicWidth;
}
// Add the width of trailing Icon.
if (child == childBefore(lastChild!)) {
width += maxIntrinsicWidth;
}
width = math.max(width, maxIntrinsicWidth);
final _DropdownMenuBodyParentData childParentData =
child.parentData! as _DropdownMenuBodyParentData;
child = childParentData.nextSibling;
}

return math.max(width, _kMinimumWidth);
}

@override
double computeMinIntrinsicHeight(double height) {
final RenderBox? child = firstChild;
double width = 0;
if (child != null) {
width = math.max(width, child.getMinIntrinsicHeight(height));
}
return width;
}

@override
double computeMaxIntrinsicHeight(double height) {
final RenderBox? child = firstChild;
double width = 0;
if (child != null) {
width = math.max(width, child.getMaxIntrinsicHeight(height));
}
return width;
}

@override
bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
final RenderBox? child = firstChild;
if (child != null) {
final _DropdownMenuBodyParentData childParentData =
child.parentData! as _DropdownMenuBodyParentData;
final bool isHit = result.addWithPaintOffset(
offset: childParentData.offset,
position: position,
hitTest: (BoxHitTestResult result, Offset transformed) {
assert(transformed == position - childParentData.offset);
return child.hitTest(result, position: transformed);
},
);
if (isHit) {
return true;
}
}
return false;
}
}

// Hand coded defaults. These will be updated once we have tokens/spec.
class _DropdownMenuDefaultsM3 extends DropdownMenuThemeData {
_DropdownMenuDefaultsM3(this.context);

final BuildContext context;
late final ThemeData _theme = Theme.of(context);

@override
TextStyle? get textStyle => _theme.textTheme.labelLarge;

@override
MenuStyle get menuStyle {
return const MenuStyle(
minimumSize: MaterialStatePropertyAll<Size>(Size(_kMinimumWidth, 0.0)),
maximumSize: MaterialStatePropertyAll<Size>(Size.infinite),
visualDensity: VisualDensity.standard,
);
}

@override
InputDecorationTheme get inputDecorationTheme {
return const InputDecorationTheme(border: OutlineInputBorder());
}
}