Skip to content

Commit a5fc3ba

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 a5fc3ba

3 files changed

Lines changed: 281 additions & 26 deletions

File tree

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import 'theme.dart';
1212

1313
/// {@macro flutter.widgets.RawAutocomplete.RawAutocomplete}
1414
///
15+
/// The options to be displayed are determined using [optionsBuilder].
16+
///
1517
/// {@youtube 560 315 https://www.youtube.com/watch?v=-Nny8kzW380}
1618
///
1719
/// {@tool dartpad}

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

Lines changed: 126 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -121,21 +121,56 @@ 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 user's text input is rendered with [fieldViewBuilder].
132164
///
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.
165+
/// The options view is rendered with [optionsViewBuilder].
166+
/// It opens when the field gains focus and there is at least one
167+
/// option available. It closes when the user selects an option, when there are
168+
/// no matching options, or when the field loses focus.
137169
/// {@endtemplate}
138170
///
171+
/// The options to be displayed are determined
172+
/// using [optionsBuilder] or [controller].
173+
///
139174
/// This is a core framework widget with very basic UI.
140175
///
141176
/// {@tool dartpad}
@@ -171,12 +206,16 @@ enum OptionsViewOpenDirection {
171206
class RawAutocomplete<T extends Object> extends StatefulWidget {
172207
/// Create an instance of RawAutocomplete.
173208
///
174-
/// [displayStringForOption], [optionsBuilder] and [optionsViewBuilder] must
175-
/// not be null.
209+
/// Exactly one of [optionsBuilder] or [controller] must be provided.
210+
/// When [optionsBuilder] is provided, the widget internally calls it when the
211+
/// text field's [TextEditingValue] changes and manages the result.
212+
/// When [controller] is provided, the caller sets
213+
/// [AutocompleteController.options] directly and the widget reacts.
176214
const RawAutocomplete({
177215
super.key,
178216
required this.optionsViewBuilder,
179-
required this.optionsBuilder,
217+
this.optionsBuilder,
218+
this.controller,
180219
this.optionsViewOpenDirection = OptionsViewOpenDirection.down,
181220
this.displayStringForOption = defaultStringForOption,
182221
this.fieldViewBuilder,
@@ -193,6 +232,10 @@ class RawAutocomplete<T extends Object> extends StatefulWidget {
193232
assert(
194233
!(textEditingController != null && initialValue != null),
195234
'textEditingController and initialValue cannot be simultaneously defined.',
235+
),
236+
assert(
237+
(optionsBuilder == null) != (controller == null),
238+
'Exactly one of optionsBuilder or controller must be provided.',
196239
);
197240

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

282339
/// The [TextEditingController] that is used for the text field.
283340
///
@@ -383,7 +440,14 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
383440
DismissIntent: CallbackAction<DismissIntent>(onInvoke: _hideOptions),
384441
};
385442

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

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

496-
// Makes sure that previous call results do not replace new ones.
497-
if (callId != _onChangedCallId) {
498-
return;
558+
if (!mounted) {
559+
return;
560+
}
561+
562+
// Makes sure that previous call results do not replace new ones.
563+
if (callId != _onChangedCallId) {
564+
return;
565+
}
566+
_controller.options = options; // triggers _handleOptionsChanged via listener
567+
} else {
568+
// External controller: caller manages options separately.
569+
// Still update selection validity and visibility for text changes.
570+
_updateSelectionValidity();
499571
}
500-
if (_options.isEmpty != options.isEmpty) {
501-
_announceSemantics(options.isNotEmpty);
572+
}
573+
574+
// No setState here: the overlay content rebuilds because
575+
// _updateOptionsViewVisibility calls show()/hide() on the
576+
// OverlayPortalController, which calls setState on _OverlayPortalState.
577+
void _handleOptionsChanged() {
578+
final bool optionsWereEmpty = _lastOptionsWereEmpty;
579+
_lastOptionsWereEmpty = _options.isEmpty;
580+
if (optionsWereEmpty != _options.isEmpty) {
581+
_announceSemantics(_options.isNotEmpty);
502582
}
503-
_options = options;
504583
_updateHighlight(_highlightedOptionIndex.value);
584+
_updateSelectionValidity();
585+
}
586+
587+
void _updateSelectionValidity() {
505588
final T? selection = _selection;
506-
if (selection != null && value.text != widget.displayStringForOption(selection)) {
589+
if (selection != null &&
590+
_textEditingController.text != widget.displayStringForOption(selection)) {
507591
_selection = null;
508592
}
509-
510593
_updateOptionsViewVisibility();
511594
}
512595

@@ -661,6 +744,10 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
661744
@override
662745
void initState() {
663746
super.initState();
747+
if (widget.controller != null) {
748+
widget.controller!.addListener(_handleOptionsChanged);
749+
_lastOptionsWereEmpty = widget.controller!.options.isEmpty;
750+
}
664751
final TextEditingController initialController =
665752
widget.textEditingController ??
666753
(_internalTextEditingController = TextEditingController.fromValue(widget.initialValue));
@@ -672,6 +759,17 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
672759
@override
673760
void didUpdateWidget(RawAutocomplete<T> oldWidget) {
674761
super.didUpdateWidget(oldWidget);
762+
if (!identical(oldWidget.controller, widget.controller)) {
763+
oldWidget.controller?.removeListener(_handleOptionsChanged);
764+
if (oldWidget.controller == null) {
765+
_internalController?.dispose();
766+
_internalController = null;
767+
}
768+
if (widget.controller != null) {
769+
widget.controller!.addListener(_handleOptionsChanged);
770+
_lastOptionsWereEmpty = widget.controller!.options.isEmpty;
771+
}
772+
}
675773
if (!identical(oldWidget.textEditingController, widget.textEditingController)) {
676774
oldWidget.textEditingController?.removeListener(_onChangedField);
677775
if (oldWidget.textEditingController == null) {
@@ -692,6 +790,8 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
692790

693791
@override
694792
void dispose() {
793+
widget.controller?.removeListener(_handleOptionsChanged);
794+
_internalController?.dispose();
695795
widget.textEditingController?.removeListener(_onChangedField);
696796
_internalTextEditingController?.dispose();
697797
widget.focusNode?.removeListener(_onFocusChange);

0 commit comments

Comments
 (0)