Skip to content

Commit b9397f2

Browse files
[material_ui] Document how to programmatically clear DropdownMenu selection (#13266)
## Description Clarifies how to programmatically clear or reset the selection in `DropdownMenu`. Setting initialSelection to null on a rebuild does not clear the text field, because DropdownMenu only updates the text field when initialSelection changes to a value that matches one of the dropdownMenuEntries. This PR documents that the selection should be cleared by providing a TextEditingController and calling controller.clear() alongside setting the state variable to null, and adds an interactive code sample demonstrating this pattern. Fixes flutter/flutter#177599 ## Pre-Review Checklist **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent 86509a5 commit b9397f2

4 files changed

Lines changed: 213 additions & 3 deletions

File tree

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// Copyright 2013 The Flutter Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
// #region body
6+
import 'package:material_ui/material_ui.dart';
7+
8+
/// Flutter code sample for [DropdownMenu] showing how to programmatically
9+
/// clear or reset the selection using a [TextEditingController].
10+
11+
void main() => runApp(const DropdownMenuClearExampleApp());
12+
13+
class DropdownMenuClearExampleApp extends StatelessWidget {
14+
const DropdownMenuClearExampleApp({super.key});
15+
16+
@override
17+
Widget build(BuildContext context) {
18+
return MaterialApp(
19+
home: Scaffold(
20+
appBar: AppBar(title: const Text('Clear DropdownMenu Sample')),
21+
body: const Center(child: DropdownMenuClearExample()),
22+
),
23+
);
24+
}
25+
}
26+
27+
class DropdownMenuClearExample extends StatefulWidget {
28+
const DropdownMenuClearExample({super.key});
29+
30+
@override
31+
State<DropdownMenuClearExample> createState() =>
32+
_DropdownMenuClearExampleState();
33+
}
34+
35+
enum ColorItem {
36+
red('Red'),
37+
green('Green'),
38+
blue('Blue');
39+
40+
const ColorItem(this.label);
41+
final String label;
42+
}
43+
44+
class _DropdownMenuClearExampleState extends State<DropdownMenuClearExample> {
45+
final TextEditingController _controller = TextEditingController();
46+
ColorItem? _selectedColor = ColorItem.red;
47+
48+
@override
49+
void dispose() {
50+
_controller.dispose();
51+
super.dispose();
52+
}
53+
54+
void _clearSelection() {
55+
setState(() {
56+
_selectedColor = null;
57+
_controller.clear();
58+
});
59+
}
60+
61+
@override
62+
Widget build(BuildContext context) {
63+
return Column(
64+
mainAxisAlignment: MainAxisAlignment.center,
65+
children: <Widget>[
66+
DropdownMenu<ColorItem>(
67+
controller: _controller,
68+
initialSelection: _selectedColor,
69+
label: const Text('Color'),
70+
onSelected: (ColorItem? color) {
71+
setState(() {
72+
_selectedColor = color;
73+
});
74+
},
75+
dropdownMenuEntries: ColorItem.values
76+
.map<DropdownMenuEntry<ColorItem>>((ColorItem color) {
77+
return DropdownMenuEntry<ColorItem>(
78+
value: color,
79+
label: color.label,
80+
);
81+
})
82+
.toList(),
83+
),
84+
const SizedBox(height: 20),
85+
FilledButton(
86+
onPressed: _clearSelection,
87+
child: const Text('Clear selection'),
88+
),
89+
const SizedBox(height: 20),
90+
Text('Selected: ${_selectedColor?.label ?? 'None'}'),
91+
],
92+
);
93+
}
94+
}
95+
// #endregion body
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// Copyright 2013 The Flutter Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
import 'package:flutter_test/flutter_test.dart';
6+
import 'package:material_ui/material_ui.dart';
7+
import 'package:material_ui_examples/dropdown_menu/dropdown_menu.3.dart'
8+
as example;
9+
10+
void main() {
11+
testWidgets('Selecting an entry updates the text field and state', (
12+
WidgetTester tester,
13+
) async {
14+
await tester.pumpWidget(const example.DropdownMenuClearExampleApp());
15+
16+
expect(find.text('Selected: Red'), findsOneWidget);
17+
expect(find.widgetWithText(TextField, 'Red'), findsOneWidget);
18+
19+
// Open menu and select Green.
20+
await tester.tap(find.byType(DropdownMenu<example.ColorItem>));
21+
await tester.pumpAndSettle();
22+
23+
await tester.tap(find.widgetWithText(MenuItemButton, 'Green').last);
24+
await tester.pumpAndSettle();
25+
26+
expect(find.text('Selected: Green'), findsOneWidget);
27+
expect(find.widgetWithText(TextField, 'Green'), findsOneWidget);
28+
});
29+
30+
testWidgets(
31+
'Pressing clear selection button resets the text field and state',
32+
(WidgetTester tester) async {
33+
await tester.pumpWidget(const example.DropdownMenuClearExampleApp());
34+
35+
// Open menu and select Blue.
36+
await tester.tap(find.byType(DropdownMenu<example.ColorItem>));
37+
await tester.pumpAndSettle();
38+
39+
await tester.tap(find.widgetWithText(MenuItemButton, 'Blue').last);
40+
await tester.pumpAndSettle();
41+
42+
expect(find.text('Selected: Blue'), findsOneWidget);
43+
expect(find.widgetWithText(TextField, 'Blue'), findsOneWidget);
44+
45+
// Tap clear button.
46+
await tester.tap(find.widgetWithText(FilledButton, 'Clear selection'));
47+
await tester.pumpAndSettle();
48+
49+
expect(find.text('Selected: None'), findsOneWidget);
50+
expect(find.widgetWithText(TextField, ''), findsOneWidget);
51+
},
52+
);
53+
54+
testWidgets('Pressing clear selection button clears the initial selection', (
55+
WidgetTester tester,
56+
) async {
57+
await tester.pumpWidget(const example.DropdownMenuClearExampleApp());
58+
59+
expect(find.text('Selected: Red'), findsOneWidget);
60+
expect(find.widgetWithText(TextField, 'Red'), findsOneWidget);
61+
62+
// Tap clear button without opening the menu.
63+
await tester.tap(find.widgetWithText(FilledButton, 'Clear selection'));
64+
await tester.pumpAndSettle();
65+
66+
expect(find.text('Selected: None'), findsOneWidget);
67+
expect(find.widgetWithText(TextField, ''), findsOneWidget);
68+
});
69+
}

‎packages/material_ui/lib/src/dropdown_menu.dart‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,33 @@ class DropdownMenu<T> extends StatefulWidget {
448448
/// Controls the text being edited or selected in the menu.
449449
///
450450
/// If null, this widget will create its own [TextEditingController].
451+
///
452+
/// A [TextEditingController] can be provided to programmatically clear or modify
453+
/// the displayed selection. For example, calling [TextEditingController.clear]
454+
/// clears the text displayed in the dropdown menu.
455+
///
456+
/// When tracking the selected value in a state variable, calling
457+
/// [TextEditingController.clear] alongside updating the state variable to null
458+
/// is required to clear the displayed selection, as setting [initialSelection]
459+
/// to null does not clear the text field.
460+
///
461+
/// <callout-box>
462+
///
463+
/// This sample demonstrates how to programmatically clear the selection in a
464+
/// [DropdownMenu] using a [TextEditingController].
465+
///
466+
// TODO(framework): Replace the following block with a @dartpad directive
467+
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
468+
/// {@macro material_ui.dartpad_guide}
469+
///
470+
/// {@example /example/lib/dropdown_menu/dropdown_menu.3.dart#body}
471+
///
472+
/// </callout-box>
473+
///
474+
/// See also:
475+
///
476+
/// * [initialSelection], which sets the initial selection when the widget is
477+
/// first created.
451478
final TextEditingController? controller;
452479

453480
/// The value used for an initial selection.
@@ -456,13 +483,29 @@ class DropdownMenu<T> extends StatefulWidget {
456483
/// is first created. If the value matches one of the [dropdownMenuEntries],
457484
/// the corresponding label will be displayed in the text field.
458485
///
459-
/// Setting this to null does not clear the text field.
486+
/// Setting this to null on a rebuild does not clear the text field, because
487+
/// [DropdownMenu] only updates the text field when [initialSelection] changes
488+
/// to a value that matches one of the [dropdownMenuEntries].
460489
///
461-
/// To programmatically clear the text field, use a [TextEditingController]
462-
/// and call [TextEditingController.clear] on it.
490+
/// To programmatically clear or reset the selection, provide a [controller]
491+
/// and call [TextEditingController.clear] on it alongside resetting the state
492+
/// variable to null.
463493
///
464494
/// Defaults to null.
465495
///
496+
/// <callout-box>
497+
///
498+
/// This sample demonstrates how to programmatically clear the selection in a
499+
/// [DropdownMenu] using a [TextEditingController].
500+
///
501+
// TODO(framework): Replace the following block with a @dartpad directive
502+
// when it's supported. https://github.com/dart-lang/dartdoc/issues/4123
503+
/// {@macro material_ui.dartpad_guide}
504+
///
505+
/// {@example /example/lib/dropdown_menu/dropdown_menu.3.dart#body}
506+
///
507+
/// </callout-box>
508+
///
466509
/// See also:
467510
///
468511
/// * [controller], which is required to programmatically clear or modify
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
changelog: |
2+
- Clarifies how to programmatically clear or reset the selection in `DropdownMenu`.
3+
version: patch

0 commit comments

Comments
 (0)