I have this method which gets a suggested place through the Google Places API based on the user input.
void getSuggestion(String input) async {
var googlePlace = GooglePlace(AppConstants.APIBASE_GOOGLEMAPS_KEY);
var result = await googlePlace.queryAutocomplete.get(input);
setState(() {
_placeList = result!.predictions!;
});
}
_placeList is filled properly, but it does not get updated instantly, I have to hot reload to see the changes whenever I change the query value in my TextController:
TextField(
onSubmitted: (value) {
setState(() {
getSuggestion(value);
showDialog(
context: context,
builder: ((context) {
return Card(
child: ListTile(
title: Text(_placeList[0].description),
),
);
}));
});
},
For example, if I search for "Miami" I get the recommendation on my listTile, but if I change it to "Madrid" it still appears "Miami" and I have to reload screen to see the change. I do not understand because I am setting the state in my method.
CodePudding user response:
getSuggestion
is an asynchronous function. In other words, in the following code snippet:
getSuggestion(value);
showDialog(
context: context,
...
After invoking getSuggestion
, it does not wait the function to finish before showing the dialog. In other words, when the dialog is shown, maybe the previous function hasn't completed yet, so that _placeList
is not updated yet.
Firstly, it is a better idea to get rid of setState
within getSuggestion
as it is redundant to do it twice.
Secondly, in the onSubmitted
lambda, make the anonymous function async (onSubmitted: (value) async { ...
), then wait for getSuggestion
to finish by await getSuggestion()
(do not await inside setState
). At this point, _placeList
is updated, and you can invoke setState
now, things should rebuild properly if there are no other errors.