Skip to content

Commit 01aa1b6

Browse files
committed
autocomplete: Add controller param for caller-managed options
Fixes flutter#159443. RawAutocomplete.optionsBuilder only receives a TextEditingValue, so it cannot react to changes in external state (e.g. a data source that loads asynchronously after focus). This adds AutocompleteController, a ChangeNotifier with an options getter/setter, and a new controller param on RawAutocomplete that is mutually exclusive with optionsBuilder. When a controller is provided, the caller sets controller.options directly and the widget reacts. Internally, the state now uses AutocompleteController for both paths: optionsBuilder results flow through an internal controller, while an external controller is used directly. The post-update work (semantics announcements, highlight clamping, selection validity, visibility) is extracted into _handleOptionsChanged, which listens to whichever controller is active.
1 parent 1130207 commit 01aa1b6

2 files changed

Lines changed: 279 additions & 24 deletions

File tree

‎packages/flutter/lib/src/widgets/autocomplete.dart‎

Lines changed: 126 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -121,21 +121,58 @@ enum OptionsViewOpenDirection {
121121
mostSpace,
122122
}
123123

124+
/// A controller for a [RawAutocomplete] widget
125+
/// that allows the caller to manage the options list directly
126+
/// instead of using a [RawAutocomplete.optionsBuilder] callback.
127+
///
128+
/// This is useful when the options depend on criteria beyond just the
129+
/// [TextEditingValue], which is the only input
130+
/// that [RawAutocomplete.optionsBuilder] receives.
131+
///
132+
/// Provide an [AutocompleteController] to [RawAutocomplete.controller] and
133+
/// set [options] to update the displayed options. The widget will react to
134+
/// changes in the controller's options and show/hide the options view
135+
/// accordingly.
136+
///
137+
/// Remember to [dispose] of the [AutocompleteController] when it is no
138+
/// longer needed. This will ensure all resources used by the object are
139+
/// discarded.
140+
///
141+
/// See also:
142+
///
143+
/// * [RawAutocomplete.controller], which accepts this controller.
144+
/// * [RawAutocomplete.optionsBuilder], the callback-based alternative.
145+
class AutocompleteController<T extends Object> extends ChangeNotifier {
146+
/// The current list of selectable options.
147+
Iterable<T> get options => _options;
148+
Iterable<T> _options = Iterable<T>.empty();
149+
set options(Iterable<T> value) {
150+
if (value == _options) {
151+
return;
152+
}
153+
_options = value;
154+
notifyListeners();
155+
}
156+
}
157+
124158
// TODO(justinmc): Mention AutocompleteCupertino when it is implemented.
125159
/// {@template flutter.widgets.RawAutocomplete.RawAutocomplete}
126160
/// A widget for helping the user make a selection by entering some text and
127161
/// choosing from among a list of options.
128162
///
129-
/// The user's text input is received in a field built with the
130-
/// [fieldViewBuilder] parameter. The options to be displayed are determined
131-
/// using [optionsBuilder] and rendered with [optionsViewBuilder].
163+
/// The text input is rendered with [fieldViewBuilder].
164+
/// The options to be displayed are determined using [optionsBuilder]
165+
/// and rendered with [optionsViewBuilder].
132166
///
133167
/// The options view opens when the field gains focus or when the field's text
134-
/// changes, as long as [optionsBuilder] returns at least one option. The options
135-
/// view closes when the user selects an option, when there are no matching
168+
/// changes, as long as there is at least one option. The options
169+
/// view closes when the user selects an option, when there are no
136170
/// options, or when the field loses focus.
137171
/// {@endtemplate}
138172
///
173+
/// Alternatively, provide a [controller] to manage the options list directly
174+
/// instead of using [optionsBuilder].
175+
///
139176
/// This is a core framework widget with very basic UI.
140177
///
141178
/// {@tool dartpad}
@@ -171,12 +208,16 @@ enum OptionsViewOpenDirection {
171208
class RawAutocomplete<T extends Object> extends StatefulWidget {
172209
/// Create an instance of RawAutocomplete.
173210
///
174-
/// [displayStringForOption], [optionsBuilder] and [optionsViewBuilder] must
175-
/// not be null.
211+
/// Exactly one of [optionsBuilder] or [controller] must be provided.
212+
/// When [optionsBuilder] is provided, the widget internally calls it when the
213+
/// text field's [TextEditingValue] changes and manages the result.
214+
/// When [controller] is provided, the caller sets
215+
/// [AutocompleteController.options] directly and the widget reacts.
176216
const RawAutocomplete({
177217
super.key,
178218
required this.optionsViewBuilder,
179-
required this.optionsBuilder,
219+
this.optionsBuilder,
220+
this.controller,
180221
this.optionsViewOpenDirection = OptionsViewOpenDirection.down,
181222
this.displayStringForOption = defaultStringForOption,
182223
this.fieldViewBuilder,
@@ -193,6 +234,10 @@ class RawAutocomplete<T extends Object> extends StatefulWidget {
193234
assert(
194235
!(textEditingController != null && initialValue != null),
195236
'textEditingController and initialValue cannot be simultaneously defined.',
237+
),
238+
assert(
239+
(optionsBuilder == null) != (controller == null),
240+
'Exactly one of optionsBuilder or controller must be provided.',
196241
);
197242

198243
/// {@template flutter.widgets.RawAutocomplete.fieldViewBuilder}
@@ -277,7 +322,21 @@ class RawAutocomplete<T extends Object> extends StatefulWidget {
277322
/// A function that returns the current selectable options objects given the
278323
/// current TextEditingValue.
279324
/// {@endtemplate}
280-
final AutocompleteOptionsBuilder<T> optionsBuilder;
325+
///
326+
/// Mutually exclusive with [controller]. Exactly one must be provided.
327+
final AutocompleteOptionsBuilder<T>? optionsBuilder;
328+
329+
/// {@template flutter.widgets.RawAutocomplete.controller}
330+
/// A controller that allows the caller to manage the options list directly.
331+
///
332+
/// When provided, the caller sets [AutocompleteController.options]
333+
/// directly and the widget reacts to changes. This is useful when the
334+
/// options depend on criteria beyond just the [TextEditingValue], which is
335+
/// the only input that [optionsBuilder] receives.
336+
/// {@endtemplate}
337+
///
338+
/// Mutually exclusive with [optionsBuilder]. Exactly one must be provided.
339+
final AutocompleteController<T>? controller;
281340

282341
/// The [TextEditingController] that is used for the text field.
283342
///
@@ -383,7 +442,14 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
383442
DismissIntent: CallbackAction<DismissIntent>(onInvoke: _hideOptions),
384443
};
385444

386-
Iterable<T> _options = Iterable<T>.empty();
445+
AutocompleteController<T>? _internalController;
446+
AutocompleteController<T> get _controller {
447+
return widget.controller ??
448+
(_internalController ??= AutocompleteController<T>()..addListener(_handleOptionsChanged));
449+
}
450+
451+
Iterable<T> get _options => _controller.options;
452+
bool _lastOptionsWereEmpty = true;
387453
T? _selection;
388454
// Set the initial value to null so when this widget gets focused for the first
389455
// time it will try to run the options view builder.
@@ -485,28 +551,47 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
485551
_userHidOptions = false;
486552
}
487553
_lastFieldText = value.text;
488-
_onChangedCallId += 1;
489-
final int callId = _onChangedCallId;
490-
final Iterable<T> options = await widget.optionsBuilder(value);
491554

492-
if (!mounted) {
493-
return;
494-
}
555+
if (widget.optionsBuilder case final optionsBuilder?) {
556+
_onChangedCallId += 1;
557+
final int callId = _onChangedCallId;
558+
final Iterable<T> options = await optionsBuilder(value);
495559

496-
// Makes sure that previous call results do not replace new ones.
497-
if (callId != _onChangedCallId) {
498-
return;
560+
if (!mounted) {
561+
return;
562+
}
563+
564+
// Makes sure that previous call results do not replace new ones.
565+
if (callId != _onChangedCallId) {
566+
return;
567+
}
568+
_controller.options = options; // triggers _handleOptionsChanged via listener
569+
} else {
570+
// External controller: caller manages options separately.
571+
// Still update selection validity and visibility for text changes.
572+
_updateSelectionValidity();
499573
}
500-
if (_options.isEmpty != options.isEmpty) {
501-
_announceSemantics(options.isNotEmpty);
574+
}
575+
576+
// No setState here: the overlay content rebuilds because
577+
// _updateOptionsViewVisibility calls show()/hide() on the
578+
// OverlayPortalController, which calls setState on _OverlayPortalState.
579+
void _handleOptionsChanged() {
580+
final bool optionsWereEmpty = _lastOptionsWereEmpty;
581+
_lastOptionsWereEmpty = _options.isEmpty;
582+
if (optionsWereEmpty != _options.isEmpty) {
583+
_announceSemantics(_options.isNotEmpty);
502584
}
503-
_options = options;
504585
_updateHighlight(_highlightedOptionIndex.value);
586+
_updateSelectionValidity();
587+
}
588+
589+
void _updateSelectionValidity() {
505590
final T? selection = _selection;
506-
if (selection != null && value.text != widget.displayStringForOption(selection)) {
591+
if (selection != null &&
592+
_textEditingController.text != widget.displayStringForOption(selection)) {
507593
_selection = null;
508594
}
509-
510595
_updateOptionsViewVisibility();
511596
}
512597

@@ -661,6 +746,10 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
661746
@override
662747
void initState() {
663748
super.initState();
749+
if (widget.controller != null) {
750+
widget.controller!.addListener(_handleOptionsChanged);
751+
_lastOptionsWereEmpty = widget.controller!.options.isEmpty;
752+
}
664753
final TextEditingController initialController =
665754
widget.textEditingController ??
666755
(_internalTextEditingController = TextEditingController.fromValue(widget.initialValue));
@@ -672,6 +761,17 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
672761
@override
673762
void didUpdateWidget(RawAutocomplete<T> oldWidget) {
674763
super.didUpdateWidget(oldWidget);
764+
if (!identical(oldWidget.controller, widget.controller)) {
765+
oldWidget.controller?.removeListener(_handleOptionsChanged);
766+
if (oldWidget.controller == null) {
767+
_internalController?.dispose();
768+
_internalController = null;
769+
}
770+
if (widget.controller != null) {
771+
widget.controller!.addListener(_handleOptionsChanged);
772+
_lastOptionsWereEmpty = widget.controller!.options.isEmpty;
773+
}
774+
}
675775
if (!identical(oldWidget.textEditingController, widget.textEditingController)) {
676776
oldWidget.textEditingController?.removeListener(_onChangedField);
677777
if (oldWidget.textEditingController == null) {
@@ -692,6 +792,8 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
692792

693793
@override
694794
void dispose() {
795+
widget.controller?.removeListener(_handleOptionsChanged);
796+
_internalController?.dispose();
695797
widget.textEditingController?.removeListener(_onChangedField);
696798
_internalTextEditingController?.dispose();
697799
widget.focusNode?.removeListener(_onFocusChange);

‎packages/flutter/test/widgets/autocomplete_test.dart‎

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4087,4 +4087,157 @@ void main() {
40874087
// Now text up to cursor is "go", which matches more options.
40884088
expect(lastOptions, <String>['dingo', 'flamingo', 'goose']);
40894089
});
4090+
4091+
group('AutocompleteController', () {
4092+
testWidgets('shows, updates, and hides options view', (WidgetTester tester) async {
4093+
final GlobalKey fieldKey = GlobalKey();
4094+
final GlobalKey optionsKey = GlobalKey();
4095+
final controller = AutocompleteController<String>();
4096+
addTearDown(controller.dispose);
4097+
late FocusNode focusNode;
4098+
late Iterable<String> lastOptions;
4099+
4100+
await tester.pumpWidget(
4101+
TestWidgetsApp(
4102+
home: RawAutocomplete<String>(
4103+
controller: controller,
4104+
fieldViewBuilder:
4105+
(
4106+
BuildContext context,
4107+
TextEditingController fieldTextEditingController,
4108+
FocusNode fieldFocusNode,
4109+
VoidCallback onFieldSubmitted,
4110+
) {
4111+
focusNode = fieldFocusNode;
4112+
return TestTextField(
4113+
key: fieldKey,
4114+
focusNode: focusNode,
4115+
controller: fieldTextEditingController,
4116+
);
4117+
},
4118+
optionsViewBuilder:
4119+
(
4120+
BuildContext context,
4121+
AutocompleteOnSelected<String> onSelected,
4122+
Iterable<String> options,
4123+
) {
4124+
lastOptions = options;
4125+
return Container(key: optionsKey);
4126+
},
4127+
),
4128+
),
4129+
);
4130+
4131+
// Set options and focus — options view shows.
4132+
controller.options = kOptions;
4133+
focusNode.requestFocus();
4134+
await tester.pump();
4135+
expect(find.byKey(optionsKey), findsOneWidget);
4136+
expect(lastOptions.length, kOptions.length);
4137+
4138+
// Update to a subset.
4139+
controller.options = <String>['aardvark', 'bobcat'];
4140+
await tester.pump();
4141+
expect(lastOptions.length, 2);
4142+
expect(lastOptions.elementAt(0), 'aardvark');
4143+
expect(lastOptions.elementAt(1), 'bobcat');
4144+
4145+
// Set to empty — options view hides.
4146+
controller.options = <String>[];
4147+
await tester.pump();
4148+
expect(find.byKey(optionsKey), findsNothing);
4149+
});
4150+
4151+
testWidgets('options stay hidden after Escape until text change or re-focus', (
4152+
WidgetTester tester,
4153+
) async {
4154+
final GlobalKey fieldKey = GlobalKey();
4155+
final GlobalKey optionsKey = GlobalKey();
4156+
final controller = AutocompleteController<String>();
4157+
addTearDown(controller.dispose);
4158+
late FocusNode focusNode;
4159+
4160+
await tester.pumpWidget(
4161+
TestWidgetsApp(
4162+
home: RawAutocomplete<String>(
4163+
controller: controller,
4164+
fieldViewBuilder:
4165+
(
4166+
BuildContext context,
4167+
TextEditingController fieldTextEditingController,
4168+
FocusNode fieldFocusNode,
4169+
VoidCallback onFieldSubmitted,
4170+
) {
4171+
focusNode = fieldFocusNode;
4172+
return TestTextField(
4173+
key: fieldKey,
4174+
focusNode: focusNode,
4175+
controller: fieldTextEditingController,
4176+
);
4177+
},
4178+
optionsViewBuilder:
4179+
(
4180+
BuildContext context,
4181+
AutocompleteOnSelected<String> onSelected,
4182+
Iterable<String> options,
4183+
) {
4184+
return Container(key: optionsKey);
4185+
},
4186+
),
4187+
),
4188+
);
4189+
4190+
// Show options.
4191+
controller.options = kOptions;
4192+
focusNode.requestFocus();
4193+
await tester.pump();
4194+
expect(find.byKey(optionsKey), findsOneWidget);
4195+
4196+
// Dismiss with Escape.
4197+
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
4198+
await tester.pump();
4199+
expect(find.byKey(optionsKey), findsNothing);
4200+
4201+
// New options from controller don't reopen the view.
4202+
controller.options = <String>['aardvark', 'bobcat'];
4203+
await tester.pump();
4204+
expect(find.byKey(optionsKey), findsNothing);
4205+
4206+
// Typing new text reopens it.
4207+
await tester.enterText(find.byKey(fieldKey), 'a');
4208+
await tester.pump();
4209+
expect(find.byKey(optionsKey), findsOneWidget);
4210+
});
4211+
4212+
testWidgets('assertion: exactly one of optionsBuilder or controller', (
4213+
WidgetTester tester,
4214+
) async {
4215+
final controller = AutocompleteController<String>();
4216+
addTearDown(controller.dispose);
4217+
4218+
Widget optionsViewBuilder(
4219+
BuildContext context,
4220+
AutocompleteOnSelected<String> onSelected,
4221+
Iterable<String> options,
4222+
) {
4223+
return Container();
4224+
}
4225+
4226+
// Both provided.
4227+
expect(
4228+
() => RawAutocomplete<String>(
4229+
optionsBuilder: (TextEditingValue value) => <String>[],
4230+
controller: controller,
4231+
optionsViewBuilder: optionsViewBuilder,
4232+
),
4233+
throwsAssertionError,
4234+
);
4235+
4236+
// Neither provided.
4237+
expect(
4238+
() => RawAutocomplete<String>(optionsViewBuilder: optionsViewBuilder),
4239+
throwsAssertionError,
4240+
);
4241+
});
4242+
});
40904243
}

0 commit comments

Comments
 (0)