Flutter Google Map Api Prediction is an awesome api to deal places that you are looking for or searching. It gives you list of places as you type in text field.
First install the plugin in your pubspec.yaml file to get the Prediction Api
flutter_google_places: ^0.3.0
As you type in your text field should receive and send the inputed text to the backend service. Flutter should use restful api to your backend service.
The backend service or api should make request to the google server using the below link.
https://maps.googleapis.com/maps/api/place/autocomplete/json?input='.$request['search_text'].'&key='.'Your key'
Here we see search_text, this is something that’s coming from Flutter front end text field.
If you want to know how to use restful api to send request to the google server go to this link.
The server side code or restful api returns json from Google api. The response from the google server should be like below
response.statusCode == 200
response.body['status'] == 'OK'
response.body['predictions']
response.body[‘predictions’] returns a list. It returns a list of Maps, So we would need to use forEach to loop through and save it in local variable of List type.
List<Prediction> _predictionList = [];
Future<List<Prediction>> searchLocation(BuildContext context, String text) async {
if(text != null && text.isNotEmpty) {
Response response = await locationRepo.searchLocation(text);
if (response.statusCode == 200 && response.body['status'] == 'OK') {
_predictionList = [];
response.body['predictions'].forEach((prediction)
=> _predictionList.add(Prediction.fromJson(prediction)));
} else {
//LApiChecker.checkApi(response);
}
}
return _predictionList;
}
The line
Response response = await locationRepo.searchLocation(text); send the text to the backend and we get List of Maps(includes our location).
After that we check the status code and status. If they are fine, we go through the response.body[‘predictions’] using forEach and save it in a local variable _predictionList List.
Prediction.fromJson() is provided by Prediction object. So you don’t need to do the fromJson on your own.
See here how to use Flutter Prediction Api