getAutocompletePredictions method
Search for places using autocomplete
Implementation
Future<List<PlacePrediction>> getAutocompletePredictions({
required String query,
String? sessionToken,
String? country, // ISO 3166-1 alpha-2 country code
List<String> types = const [], // establishment, address, geocode, etc.
}) async {
if (!isInitialized) {
throw Exception('Google Places API key not initialized. Call initialize() first.');
}
if (query.trim().isEmpty) {
return [];
}
try {
final uri = Uri.parse('$_baseUrl/autocomplete/json').replace(queryParameters: {
'input': query,
'key': _apiKey!,
if (sessionToken != null) 'sessiontoken': sessionToken,
if (country != null) 'components': 'country:$country',
if (types.isNotEmpty) 'types': types.join('|'),
});
final response = await http.get(uri);
if (response.statusCode == 200) {
final data = json.decode(response.body);
if (data['status'] == 'OK') {
final predictions = data['predictions'] as List<dynamic>;
return predictions
.map((prediction) => PlacePrediction.fromJson(prediction))
.toList();
} else {
throw Exception('Google Places API error: ${data['status']} - ${data['error_message'] ?? 'Unknown error'}');
}
} else {
throw Exception('HTTP error: ${response.statusCode}');
}
} catch (e) {
throw Exception('Failed to get autocomplete predictions: $e');
}
}