fetchCountries method
Fetches the list of countries from the API.
Makes a GET request to https://chat.jobkar.in/countries.
Parses the JSON response, extracts the list of country data,
and converts each JSON object into an AwesomeCountry model.
Returns a Future<List<AwesomeCountry>> that completes with the list of countries.
Throws an Exception if the request fails or JSON parsing fails.
Implementation
Future<List<Country>> fetchCountries() async {
try {
// Make the GET HTTP request to the countries endpoint
final response = await http.get(
Uri.parse('$baseUrl/countries'), // Construct the full URL
headers: {
// Headers to allow cross-origin requests and specify content type
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Content-Type": "application/json",
},
);
// Check if the HTTP status code indicates success (200 OK)
if (response.statusCode == 200) {
// Decode the JSON response body to a Dart Map
final List data = json.decode(response.body)['data'];
// Map each JSON object in the list to an AwesomeCountry instance
return data.map((e) => Country.fromJson(e)).toList();
} else {
// If server returned an error status, throw an exception with message
throw Exception('Failed to load countries');
}
} catch (err) {
// Catch and rethrow any errors (network, parsing, etc)
throw Exception(err);
}
}