fetchSuggestions method
includeFullSuggestionDetails
if we should include ALL details that are returned in API suggestions.
(This is sent as true when the onInitialSuggestionClick
is in use)
postalCodeLookup
if we should request postal_code
type return information
instead of address type information.
Implementation
Future<List<Suggestion>> fetchSuggestions(String input,
{bool includeFullSuggestionDetails = false,
bool postalCodeLookup = false}) async {
final Map<String, dynamic> parameters = <String, dynamic>{
'input': input,
'types': postalCodeLookup
? 'postal_code'
: 'address', // this is for looking up fully qualified addresses
// Could be used for ZIP lookups// 'types': 'postal_code',
'key': mapsApiKey,
'sessiontoken': sessionToken
};
if (language != null) {
parameters.addAll(<String, dynamic>{'language': language});
}
if (compomentCountry != null) {
parameters
.addAll(<String, dynamic>{'components': 'country:$compomentCountry'});
}
final Uri request = Uri(
scheme: 'https',
host: 'maps.googleapis.com',
path: '/maps/api/place/autocomplete/json',
queryParameters: parameters);
final response = await client.get(request);
if (response.statusCode == 200) {
final result = json.decode(response.body);
if (result['status'] == 'OK') {
if (debugJson) {
printJson(result['predictions'],
title: 'GOOGLE MAP API RETURN VALUE result["predictions"]');
}
// compose suggestions in a list
return result['predictions'].map<Suggestion>((p) {
if (includeFullSuggestionDetails) {
// Package everything useful from API json
final mainText = p['structured_formatting']?['main_text'];
final secondaryText = p['structured_formatting']?['secondary_text'];
final terms = p['terms']
.map<String>((term) => term['value'] as String)
.toList();
final types =
p['types'].map<String>((atype) => atype as String).toList();
return Suggestion(p['place_id'], p['description'],
mainText: mainText,
secondaryText: secondaryText,
terms: terms,
types: types);
} else {
// just use the simple Suggestion parts we need
return Suggestion(p['place_id'], p['description']);
}
}).toList();
}
if (result['status'] == 'ZERO_RESULTS') {
return [];
}
throw Exception(result['error_message']);
} else {
throw Exception('Failed to fetch suggestion');
}
}