fetchCities method
Fetches the list of cities for a given state ID.
Makes a GET request to https://chat.jobkar.in/cities/{stateId}.
Parses the JSON response, extracts the list of city data,
and converts each JSON object into an AwesomeCity model.
Returns a Future<List<AwesomeCity>> that completes with the list of cities.
Throws an Exception if the request fails.
Implementation
Future<List<Cities>> fetchCities(int stateId) async {
// Make GET request to cities endpoint with stateId path parameter
final response = await http.get(
Uri.parse('$baseUrl/cities/$stateId'),
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Content-Type": "application/json",
},
);
// Check if the response was successful
if (response.statusCode == 200) {
// Decode JSON and convert list to AwesomeCity instances
final List data = json.decode(response.body)['data'];
return data.map((e) => Cities.fromJson(e)).toList();
} else {
// Throw error if the request failed
throw Exception('Failed to load cities');
}
}