fetchStates method

Future<List<States>> fetchStates(
  1. int countryId
)

Fetches the list of states for a given country ID.

Makes a GET request to https://chat.jobkar.in/states/{countryId}. Parses the JSON response, extracts the list of state data, and converts each JSON object into an AwesomeState model.

Returns a Future<List<AwesomeState>> that completes with the list of states. Throws an Exception if the request fails.

Implementation

Future<List<States>> fetchStates(int countryId) async {
  // Make the GET HTTP request to the states endpoint with countryId path parameter
  final response = await http.get(
    Uri.parse('$baseUrl/states/$countryId'), // Construct URL with countryId
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
      "Content-Type": "application/json",
    },
  );

  // Check for success status code
  if (response.statusCode == 200) {
    // Parse JSON and convert list to model objects
    final List data = json.decode(response.body)['data'];
    return data.map((e) => States.fromJson(e)).toList();
  } else {
    // Throw error if response is not successful
    throw Exception('Failed to load states');
  }
}