Reputation: 11
I'm trying to combine Material Autocomplete widget with Bloc pattern for Google Place Autocomplete function.
My code as below:
BlocBuilder<MyBloc, MyState>(
builder: (context, state) {
final bloc = context.read<MyBloc>();
return Autocomplete<GooglePlace>(
optionsBuilder: (textEditingValue) {
bloc.add(MakeAutocompleteEvent(textEditingValue));
return state.places;// << this line does not return the value of current state when I emit the state after making autocompletes request
}
...
Autocomplete class
With this approach, in optionsBuilder
, the widget call for text changed and return the Iterable of result in the same function.
We can await and callling API for result, then return the result here.
But this won't work for bloc pattern.
Tried to set value to textEditingController
after making the request and the state has the data, the widget rebuilt but the optionsBuilder
was not called.
I expect to make Autocomplete work with Bloc pattern.
Is there any approach for this combination? Thank you.
Upvotes: 1
Views: 46
Reputation: 11
This is exactly what I'm looking for: "Waiting for state change"
// Add event to bloc
bloc.add(MakeAutocompleteEvent(textEditingValue.text));
// Wait for successful or failed state to be emitted
// Change the condition for the state you want to get here
final newState = await bloc.stream.firstWhere((state) =>
state.status is SubmissionSuccess || state.status is SubmissionFailed);
// Check and return
if (newState.status is SubmissionSuccess) {
return newState.places;
} else {
return const Iterable.empty();
}
Upvotes: 0