Skip to content

Commit e6490f7

Browse files
committed
RawAutocomplete: 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 RawAutocompleteController, 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 RawAutocompleteController 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 e6490f7

2 files changed

Lines changed: 275 additions & 24 deletions

File tree

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

Lines changed: 122 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -121,19 +121,53 @@ 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 a [RawAutocompleteController] 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 [RawAutocompleteController] 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 RawAutocompleteController<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
///
129163
/// The user's text input is received in a field built with the
130164
/// [fieldViewBuilder] parameter. The options to be displayed are determined
131-
/// using [optionsBuilder] and rendered with [optionsViewBuilder].
165+
/// using [optionsBuilder] or [controller]
166+
/// and rendered with [optionsViewBuilder].
132167
///
133-
/// 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
136-
/// options, or when the field loses focus.
168+
/// The options view opens when the field gains focus and there is at least one
169+
/// option available. It closes when the user selects an option, when there are
170+
/// no matching options, or when the field loses focus.
137171
/// {@endtemplate}
138172
///
139173
/// This is a core framework widget with very basic UI.
@@ -171,12 +205,16 @@ enum OptionsViewOpenDirection {
171205
class RawAutocomplete<T extends Object> extends StatefulWidget {
172206
/// Create an instance of RawAutocomplete.
173207
///
174-
/// [displayStringForOption], [optionsBuilder] and [optionsViewBuilder] must
175-
/// not be null.
208+
/// Exactly one of [optionsBuilder] or [controller] must be provided.
209+
/// When [optionsBuilder] is provided, the widget internally calls it when the
210+
/// text field's [TextEditingValue] changes and manages the result.
211+
/// When [controller] is provided, the caller sets
212+
/// [RawAutocompleteController.options] directly and the widget reacts.
176213
const RawAutocomplete({
177214
super.key,
178215
required this.optionsViewBuilder,
179-
required this.optionsBuilder,
216+
this.optionsBuilder,
217+
this.controller,
180218
this.optionsViewOpenDirection = OptionsViewOpenDirection.down,
181219
this.displayStringForOption = defaultStringForOption,
182220
this.fieldViewBuilder,
@@ -193,6 +231,10 @@ class RawAutocomplete<T extends Object> extends StatefulWidget {
193231
assert(
194232
!(textEditingController != null && initialValue != null),
195233
'textEditingController and initialValue cannot be simultaneously defined.',
234+
),
235+
assert(
236+
(optionsBuilder == null) != (controller == null),
237+
'Exactly one of optionsBuilder or controller must be provided.',
196238
);
197239

198240
/// {@template flutter.widgets.RawAutocomplete.fieldViewBuilder}
@@ -277,7 +319,19 @@ class RawAutocomplete<T extends Object> extends StatefulWidget {
277319
/// A function that returns the current selectable options objects given the
278320
/// current TextEditingValue.
279321
/// {@endtemplate}
280-
final AutocompleteOptionsBuilder<T> optionsBuilder;
322+
///
323+
/// Mutually exclusive with [controller]. Exactly one must be provided.
324+
final AutocompleteOptionsBuilder<T>? optionsBuilder;
325+
326+
/// A controller that allows the caller to manage the options list directly.
327+
///
328+
/// When provided, the caller sets [RawAutocompleteController.options]
329+
/// directly and the widget reacts to changes. This is useful when the
330+
/// options depend on criteria beyond just the [TextEditingValue], which is
331+
/// the only input that [optionsBuilder] receives.
332+
///
333+
/// Mutually exclusive with [optionsBuilder]. Exactly one must be provided.
334+
final RawAutocompleteController<T>? controller;
281335

282336
/// The [TextEditingController] that is used for the text field.
283337
///
@@ -383,7 +437,15 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
383437
DismissIntent: CallbackAction<DismissIntent>(onInvoke: _hideOptions),
384438
};
385439

386-
Iterable<T> _options = Iterable<T>.empty();
440+
RawAutocompleteController<T>? _internalController;
441+
RawAutocompleteController<T> get _controller {
442+
return widget.controller ??
443+
(_internalController ??= RawAutocompleteController<T>()
444+
..addListener(_handleOptionsChanged));
445+
}
446+
447+
Iterable<T> get _options => _controller.options;
448+
bool _lastOptionsWereEmpty = true;
387449
T? _selection;
388450
// Set the initial value to null so when this widget gets focused for the first
389451
// time it will try to run the options view builder.
@@ -485,28 +547,47 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
485547
_userHidOptions = false;
486548
}
487549
_lastFieldText = value.text;
488-
_onChangedCallId += 1;
489-
final int callId = _onChangedCallId;
490-
final Iterable<T> options = await widget.optionsBuilder(value);
491550

492-
if (!mounted) {
493-
return;
494-
}
551+
if (widget.optionsBuilder case final optionsBuilder?) {
552+
_onChangedCallId += 1;
553+
final int callId = _onChangedCallId;
554+
final Iterable<T> options = await optionsBuilder(value);
495555

496-
// Makes sure that previous call results do not replace new ones.
497-
if (callId != _onChangedCallId) {
498-
return;
556+
if (!mounted) {
557+
return;
558+
}
559+
560+
// Makes sure that previous call results do not replace new ones.
561+
if (callId != _onChangedCallId) {
562+
return;
563+
}
564+
_controller.options = options; // triggers _handleOptionsChanged via listener
565+
} else {
566+
// External controller: caller manages options separately.
567+
// Still update selection validity and visibility for text changes.
568+
_updateSelectionValidity();
499569
}
500-
if (_options.isEmpty != options.isEmpty) {
501-
_announceSemantics(options.isNotEmpty);
570+
}
571+
572+
// No setState here: the overlay content rebuilds because
573+
// _updateOptionsViewVisibility calls show()/hide() on the
574+
// OverlayPortalController, which calls setState on _OverlayPortalState.
575+
void _handleOptionsChanged() {
576+
final bool optionsWereEmpty = _lastOptionsWereEmpty;
577+
_lastOptionsWereEmpty = _options.isEmpty;
578+
if (optionsWereEmpty != _options.isEmpty) {
579+
_announceSemantics(_options.isNotEmpty);
502580
}
503-
_options = options;
504581
_updateHighlight(_highlightedOptionIndex.value);
582+
_updateSelectionValidity();
583+
}
584+
585+
void _updateSelectionValidity() {
505586
final T? selection = _selection;
506-
if (selection != null && value.text != widget.displayStringForOption(selection)) {
587+
if (selection != null &&
588+
_textEditingController.text != widget.displayStringForOption(selection)) {
507589
_selection = null;
508590
}
509-
510591
_updateOptionsViewVisibility();
511592
}
512593

@@ -661,6 +742,10 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
661742
@override
662743
void initState() {
663744
super.initState();
745+
if (widget.controller != null) {
746+
widget.controller!.addListener(_handleOptionsChanged);
747+
_lastOptionsWereEmpty = widget.controller!.options.isEmpty;
748+
}
664749
final TextEditingController initialController =
665750
widget.textEditingController ??
666751
(_internalTextEditingController = TextEditingController.fromValue(widget.initialValue));
@@ -672,6 +757,17 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
672757
@override
673758
void didUpdateWidget(RawAutocomplete<T> oldWidget) {
674759
super.didUpdateWidget(oldWidget);
760+
if (!identical(oldWidget.controller, widget.controller)) {
761+
oldWidget.controller?.removeListener(_handleOptionsChanged);
762+
if (oldWidget.controller == null) {
763+
_internalController?.dispose();
764+
_internalController = null;
765+
}
766+
if (widget.controller != null) {
767+
widget.controller!.addListener(_handleOptionsChanged);
768+
_lastOptionsWereEmpty = widget.controller!.options.isEmpty;
769+
}
770+
}
675771
if (!identical(oldWidget.textEditingController, widget.textEditingController)) {
676772
oldWidget.textEditingController?.removeListener(_onChangedField);
677773
if (oldWidget.textEditingController == null) {
@@ -692,6 +788,8 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
692788

693789
@override
694790
void dispose() {
791+
widget.controller?.removeListener(_handleOptionsChanged);
792+
_internalController?.dispose();
695793
widget.textEditingController?.removeListener(_onChangedField);
696794
_internalTextEditingController?.dispose();
697795
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('RawAutocompleteController', () {
4092+
testWidgets('shows, updates, and hides options view', (WidgetTester tester) async {
4093+
final GlobalKey fieldKey = GlobalKey();
4094+
final GlobalKey optionsKey = GlobalKey();
4095+
final controller = RawAutocompleteController<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 = RawAutocompleteController<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 = RawAutocompleteController<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)