fetchSuggestions method

Future<List<Suggestion>> fetchSuggestions(
  1. String input
)

Implementation

Future<List<Suggestion>> fetchSuggestions(String input) async {
  final Map<String, dynamic> parameters = <String, dynamic>{
    'input': input,
    'types': 'address',
    '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') {
      // compose suggestions in a list
      return result['predictions']
          .map<Suggestion>((p) => 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');
  }
}