Skip to content

Commit 856069a

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 856069a

4 files changed

Lines changed: 418 additions & 27 deletions

File tree

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

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,16 @@ import 'theme.dart';
5858
/// contains more detailed examples.
5959
class Autocomplete<T extends Object> extends StatelessWidget {
6060
/// Creates an instance of [Autocomplete].
61+
///
62+
/// Exactly one of [optionsBuilder] or [controller] must be provided.
63+
/// When [optionsBuilder] is provided, the widget internally calls it when the
64+
/// text field's [TextEditingValue] changes and manages the result.
65+
/// When [controller] is provided, the caller sets
66+
/// [AutocompleteController.options] directly and the widget reacts.
6167
const Autocomplete({
6268
super.key,
63-
required this.optionsBuilder,
69+
this.optionsBuilder,
70+
this.controller,
6471
this.displayStringForOption = RawAutocomplete.defaultStringForOption,
6572
this.fieldViewBuilder = _defaultFieldViewBuilder,
6673
this.focusNode,
@@ -70,7 +77,10 @@ class Autocomplete<T extends Object> extends StatelessWidget {
7077
this.optionsViewOpenDirection = OptionsViewOpenDirection.down,
7178
this.textEditingController,
7279
this.initialValue,
73-
});
80+
}) : assert(
81+
(optionsBuilder == null) != (controller == null),
82+
'Exactly one of optionsBuilder or controller must be provided.',
83+
);
7484

7585
/// {@macro flutter.widgets.RawAutocomplete.displayStringForOption}
7686
final AutocompleteOptionToString<T> displayStringForOption;
@@ -93,7 +103,14 @@ class Autocomplete<T extends Object> extends StatelessWidget {
93103
final AutocompleteOnSelected<T>? onSelected;
94104

95105
/// {@macro flutter.widgets.RawAutocomplete.optionsBuilder}
96-
final AutocompleteOptionsBuilder<T> optionsBuilder;
106+
///
107+
/// Mutually exclusive with [controller]. Exactly one must be provided.
108+
final AutocompleteOptionsBuilder<T>? optionsBuilder;
109+
110+
/// {@macro flutter.widgets.RawAutocomplete.controller}
111+
///
112+
/// Mutually exclusive with [optionsBuilder]. Exactly one must be provided.
113+
final AutocompleteController<T>? controller;
97114

98115
/// {@macro flutter.widgets.RawAutocomplete.optionsViewBuilder}
99116
///
@@ -144,6 +161,7 @@ class Autocomplete<T extends Object> extends StatelessWidget {
144161
textEditingController: textEditingController,
145162
initialValue: initialValue,
146163
optionsBuilder: optionsBuilder,
164+
controller: controller,
147165
optionsViewOpenDirection: optionsViewOpenDirection,
148166
optionsViewBuilder:
149167
optionsViewBuilder ??

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

Lines changed: 123 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 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
///
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+
/// [AutocompleteController.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,21 @@ 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+
/// {@template flutter.widgets.RawAutocomplete.controller}
327+
/// A controller that allows the caller to manage the options list directly.
328+
///
329+
/// When provided, the caller sets [AutocompleteController.options]
330+
/// directly and the widget reacts to changes. This is useful when the
331+
/// options depend on criteria beyond just the [TextEditingValue], which is
332+
/// the only input that [optionsBuilder] receives.
333+
/// {@endtemplate}
334+
///
335+
/// Mutually exclusive with [optionsBuilder]. Exactly one must be provided.
336+
final AutocompleteController<T>? controller;
281337

282338
/// The [TextEditingController] that is used for the text field.
283339
///
@@ -383,7 +439,14 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
383439
DismissIntent: CallbackAction<DismissIntent>(onInvoke: _hideOptions),
384440
};
385441

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

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

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

@@ -661,6 +743,10 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
661743
@override
662744
void initState() {
663745
super.initState();
746+
if (widget.controller != null) {
747+
widget.controller!.addListener(_handleOptionsChanged);
748+
_lastOptionsWereEmpty = widget.controller!.options.isEmpty;
749+
}
664750
final TextEditingController initialController =
665751
widget.textEditingController ??
666752
(_internalTextEditingController = TextEditingController.fromValue(widget.initialValue));
@@ -672,6 +758,17 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
672758
@override
673759
void didUpdateWidget(RawAutocomplete<T> oldWidget) {
674760
super.didUpdateWidget(oldWidget);
761+
if (!identical(oldWidget.controller, widget.controller)) {
762+
oldWidget.controller?.removeListener(_handleOptionsChanged);
763+
if (oldWidget.controller == null) {
764+
_internalController?.dispose();
765+
_internalController = null;
766+
}
767+
if (widget.controller != null) {
768+
widget.controller!.addListener(_handleOptionsChanged);
769+
_lastOptionsWereEmpty = widget.controller!.options.isEmpty;
770+
}
771+
}
675772
if (!identical(oldWidget.textEditingController, widget.textEditingController)) {
676773
oldWidget.textEditingController?.removeListener(_onChangedField);
677774
if (oldWidget.textEditingController == null) {
@@ -692,6 +789,8 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>>
692789

693790
@override
694791
void dispose() {
792+
widget.controller?.removeListener(_handleOptionsChanged);
793+
_internalController?.dispose();
695794
widget.textEditingController?.removeListener(_onChangedField);
696795
_internalTextEditingController?.dispose();
697796
widget.focusNode?.removeListener(_onFocusChange);

0 commit comments

Comments
 (0)