Make DropdownMenu TextField reactive to label changes (#162062)

## Description

The current behavior of Flutter regarding `DropdownMenu` text field is
very basic: `DropdownMenu` updates the text field once a selection has
been made with its coordinating `label`, and nothing more.

If the selection's `label` changes, the text field will still show the
old value, although the menu buttons have been updated.

This not only results in the need to write a lot of boilerplate code to
match the label to the current selection, but it's also
counterintuitive. The `DropdownMenu` should handle rematching by itself.

Issue #155660, touched on this, and a solution was introduced in
#155757. It was later reverted due to it restricting some use cases.
That issue & solution, however, only address `initialSelection`. If
another selection was made and its corresponding `label` was changed,
the text field would still show the old value, bringing us back to
square one.

This PR should not conflict with any previous behavior of
`DropdownMenu`: any new value provided by `initialSelection` or via
controller would not be overwritten by rematching. However, entries with
the same value will be mapped to a single label (the first matched
entry's label).

## Related Issues

- Fixes #155660.

## Tests

Added 3 tests.

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [x] I signed the [CLA].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I updated/added relevant documentation (doc comments with `///`).
- [x] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [x] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [x] All existing and new tests are passing.
This commit is contained in:
Ahmed R. 2025-06-12 02:08:37 +03:00 committed by GitHub
parent 85cef5f226
commit 4e0c01066e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 229 additions and 26 deletions

View File

@ -561,16 +561,17 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
double? leadingPadding;
bool _menuHasEnabledItem = false;
TextEditingController? _localTextEditingController;
TextEditingController get _effectiveTextEditingController =>
widget.controller ?? (_localTextEditingController ??= TextEditingController());
final FocusNode _internalFocudeNode = FocusNode();
int? _selectedEntryIndex;
late final void Function() _clearSelectedEntryIndex;
@override
void initState() {
super.initState();
if (widget.controller != null) {
_localTextEditingController = widget.controller;
} else {
_localTextEditingController = TextEditingController();
}
_clearSelectedEntryIndex = () => _selectedEntryIndex = null;
_effectiveTextEditingController.addListener(_clearSelectedEntryIndex);
_enableSearch = widget.enableSearch;
filteredEntries = widget.dropdownMenuEntries;
buttonItemKeys = List<GlobalKey>.generate(filteredEntries.length, (int index) => GlobalKey());
@ -579,20 +580,20 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
(DropdownMenuEntry<T> entry) => entry.value == widget.initialSelection,
);
if (index != -1) {
_localTextEditingController?.value = TextEditingValue(
_effectiveTextEditingController.value = TextEditingValue(
text: filteredEntries[index].label,
selection: TextSelection.collapsed(offset: filteredEntries[index].label.length),
);
_selectedEntryIndex = index;
}
refreshLeadingPadding();
}
@override
void dispose() {
if (widget.controller == null) {
_localTextEditingController?.dispose();
_localTextEditingController = null;
}
widget.controller?.removeListener(_clearSelectedEntryIndex);
_localTextEditingController?.dispose();
_localTextEditingController = null;
_internalFocudeNode.dispose();
super.dispose();
}
@ -601,10 +602,11 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
void didUpdateWidget(DropdownMenu<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) {
if (widget.controller != null && oldWidget.controller == null) {
_localTextEditingController?.dispose();
}
_localTextEditingController = widget.controller ?? TextEditingController();
oldWidget.controller?.removeListener(_clearSelectedEntryIndex);
_localTextEditingController?.dispose();
_localTextEditingController = null;
_effectiveTextEditingController.addListener(_clearSelectedEntryIndex);
_selectedEntryIndex = null;
}
if (oldWidget.enableFilter != widget.enableFilter) {
if (!widget.enableFilter) {
@ -622,6 +624,21 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
filteredEntries = widget.dropdownMenuEntries;
buttonItemKeys = List<GlobalKey>.generate(filteredEntries.length, (int index) => GlobalKey());
_menuHasEnabledItem = filteredEntries.any((DropdownMenuEntry<T> entry) => entry.enabled);
if (_selectedEntryIndex != null) {
final T oldSelectionValue = oldWidget.dropdownMenuEntries[_selectedEntryIndex!].value;
final int index = filteredEntries.indexWhere(
(DropdownMenuEntry<T> entry) => entry.value == oldSelectionValue,
);
if (index != -1) {
_effectiveTextEditingController.value = TextEditingValue(
text: filteredEntries[index].label,
selection: TextSelection.collapsed(offset: filteredEntries[index].label.length),
);
_selectedEntryIndex = index;
} else {
_selectedEntryIndex = null;
}
}
}
if (oldWidget.leadingIcon != widget.leadingIcon) {
refreshLeadingPadding();
@ -631,10 +648,11 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
(DropdownMenuEntry<T> entry) => entry.value == widget.initialSelection,
);
if (index != -1) {
_localTextEditingController?.value = TextEditingValue(
_effectiveTextEditingController.value = TextEditingValue(
text: filteredEntries[index].label,
selection: TextSelection.collapsed(offset: filteredEntries[index].label.length),
);
_selectedEntryIndex = index;
}
}
}
@ -690,7 +708,7 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
}
bool _shouldUpdateCurrentHighlight(List<DropdownMenuEntry<T>> entries) {
final String searchText = _localTextEditingController!.value.text.toLowerCase();
final String searchText = _effectiveTextEditingController.value.text.toLowerCase();
if (searchText.isEmpty) {
return true;
}
@ -821,10 +839,22 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
onPressed:
entry.enabled && widget.enabled
? () {
_localTextEditingController?.value = TextEditingValue(
if (!mounted) {
// In some cases (e.g., nested menus), calling onSelected from MenuAnchor inside a postFrameCallback
// can result in the MenuItemButton's onPressed callback being triggered after the state has been disposed.
// TODO(ahmedrasar): MenuAnchor should avoid calling onSelected inside a postFrameCallback.
widget.controller?.value = TextEditingValue(
text: entry.label,
selection: TextSelection.collapsed(offset: entry.label.length),
);
widget.onSelected?.call(entry.value);
return;
}
_effectiveTextEditingController.value = TextEditingValue(
text: entry.label,
selection: TextSelection.collapsed(offset: entry.label.length),
);
_selectedEntryIndex = i;
currentHighlight = widget.enableSearch ? i : null;
widget.onSelected?.call(entry.value);
_enableFilter = false;
@ -864,7 +894,7 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
currentHighlight = (currentHighlight! - 1) % filteredEntries.length;
}
final String currentLabel = filteredEntries[currentHighlight!].label;
_localTextEditingController?.value = TextEditingValue(
_effectiveTextEditingController.value = TextEditingValue(
text: currentLabel,
selection: TextSelection.collapsed(offset: currentLabel.length),
);
@ -884,7 +914,7 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
currentHighlight = (currentHighlight! + 1) % filteredEntries.length;
}
final String currentLabel = filteredEntries[currentHighlight!].label;
_localTextEditingController?.value = TextEditingValue(
_effectiveTextEditingController.value = TextEditingValue(
text: currentLabel,
selection: TextSelection.collapsed(offset: currentLabel.length),
);
@ -898,7 +928,7 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
} else {
filteredEntries = widget.dropdownMenuEntries;
// close to open
if (_localTextEditingController!.text.isNotEmpty) {
if (_effectiveTextEditingController.text.isNotEmpty) {
_enableFilter = false;
}
controller.open();
@ -913,10 +943,11 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
if (currentHighlight != null) {
final DropdownMenuEntry<T> entry = filteredEntries[currentHighlight!];
if (entry.enabled) {
_localTextEditingController?.value = TextEditingValue(
_effectiveTextEditingController.value = TextEditingValue(
text: entry.label,
selection: TextSelection.collapsed(offset: entry.label.length),
);
_selectedEntryIndex = currentHighlight;
widget.onSelected?.call(entry.value);
}
} else {
@ -947,8 +978,8 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
if (_enableFilter) {
filteredEntries =
widget.filterCallback?.call(filteredEntries, _localTextEditingController!.text) ??
filter(widget.dropdownMenuEntries, _localTextEditingController!);
widget.filterCallback?.call(filteredEntries, _effectiveTextEditingController.text) ??
filter(widget.dropdownMenuEntries, _effectiveTextEditingController);
}
_menuHasEnabledItem = filteredEntries.any((DropdownMenuEntry<T> entry) => entry.enabled);
@ -956,12 +987,12 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
if (widget.searchCallback != null) {
currentHighlight = widget.searchCallback!(
filteredEntries,
_localTextEditingController!.text,
_effectiveTextEditingController.text,
);
} else {
final bool shouldUpdateCurrentHighlight = _shouldUpdateCurrentHighlight(filteredEntries);
if (shouldUpdateCurrentHighlight) {
currentHighlight = search(filteredEntries, _localTextEditingController!);
currentHighlight = search(filteredEntries, _effectiveTextEditingController);
}
}
if (currentHighlight != null) {
@ -1060,7 +1091,7 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
maxLines: widget.maxLines,
textInputAction: widget.textInputAction,
style: effectiveTextStyle,
controller: _localTextEditingController,
controller: _effectiveTextEditingController,
onEditingComplete: _handleEditingComplete,
onTap:
!widget.enabled

View File

@ -2442,6 +2442,178 @@ void main() {
},
);
testWidgets('Rematch selection against the first entry with the same value', (
WidgetTester tester,
) async {
final TextEditingController controller = TextEditingController();
addTearDown(controller.dispose);
String selectionLabel = 'Initial label';
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
body: DropdownMenu<TestMenu>(
initialSelection: TestMenu.mainMenu0,
dropdownMenuEntries: <DropdownMenuEntry<TestMenu>>[
DropdownMenuEntry<TestMenu>(
value: TestMenu.mainMenu0,
label: '$selectionLabel 0',
),
DropdownMenuEntry<TestMenu>(
value: TestMenu.mainMenu1,
label: '$selectionLabel 1',
),
],
controller: controller,
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => selectionLabel = 'Updated label'),
),
);
},
),
),
);
// Open the menu
await tester.tap(find.byType(DropdownMenu<TestMenu>));
await tester.pump();
// Select the second item
await tester.tap(findMenuItemButton('$selectionLabel 1'));
await tester.pump();
// Update dropdownMenuEntries labels
await tester.tap(find.byType(FloatingActionButton));
await tester.pump();
expect(controller.text, 'Updated label 1');
});
testWidgets('Forget selection if its value does not map to any entry', (
WidgetTester tester,
) async {
final TextEditingController controller = TextEditingController();
addTearDown(controller.dispose);
String selectionLabel = 'Initial label';
bool selectionInEntries = true;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
body: Column(
children: <Widget>[
DropdownMenu<TestMenu>(
initialSelection: TestMenu.mainMenu0,
dropdownMenuEntries: <DropdownMenuEntry<TestMenu>>[
DropdownMenuEntry<TestMenu>(
value: TestMenu.mainMenu0,
label: '$selectionLabel 0',
),
if (selectionInEntries)
DropdownMenuEntry<TestMenu>(
value: TestMenu.mainMenu1,
label: '$selectionLabel 1',
),
],
controller: controller,
),
ElevatedButton(
onPressed: () => setState(() => selectionInEntries = !selectionInEntries),
child: null,
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => selectionLabel = 'Updated label'),
),
);
},
),
),
);
// Open the menu
await tester.tap(find.byType(DropdownMenu<TestMenu>));
await tester.pump();
// Select the second item
await tester.tap(findMenuItemButton('$selectionLabel 1'));
await tester.pump();
// Update dropdownMenuEntries labels
await tester.tap(find.byType(FloatingActionButton));
// Remove second item from entires
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
expect(controller.text, 'Initial label 1');
// Put second item back into entries
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
expect(controller.text, 'Initial label 1');
});
testWidgets(
'Do not rematch selection if the text field was edited progrmaticlly via controller',
(WidgetTester tester) async {
final TextEditingController controller = TextEditingController();
addTearDown(controller.dispose);
String selectionLabel = 'Initial label';
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
body: Column(
children: <Widget>[
DropdownMenu<TestMenu>(
initialSelection: TestMenu.mainMenu0,
dropdownMenuEntries: <DropdownMenuEntry<TestMenu>>[
DropdownMenuEntry<TestMenu>(
value: TestMenu.mainMenu0,
label: '$selectionLabel 0',
),
],
controller: controller,
),
ElevatedButton(
onPressed: () => setState(() => controller.text = 'Controller Value'),
child: null,
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => selectionLabel = 'Updated label'),
),
);
},
),
),
);
// Change the text field value via controller
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
// Update dropdownMenuEntries labels
await tester.tap(find.byType(FloatingActionButton));
await tester.pump();
expect(controller.text, 'Controller Value');
},
);
testWidgets('The default text input field should not be focused on mobile platforms '
'when it is tapped', (WidgetTester tester) async {
final ThemeData themeData = ThemeData();