To convert the JSON data into an array in Flutter, you can use the json.decode function to convert the JSON string into a map, and then access the array using the keys and indexes.
Here's an example of how you can get the cities and counters as arrays from your JSON data:
Future<List<Map<String, dynamic>>> fetchCityCounterDetail(int id) async {
final url = 'myapi_url';
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final data = json.decode(response.body);
final List<dynamic> successList = data["responseBody"]["success"];
final List<Map<String, dynamic>> citiesAndCounters = [];
successList.forEach((success) {
final Map<String, dynamic> cityAndCounters = {
"city": success["city"],
"counters": success["counters"],
};
citiesAndCounters.add(cityAndCounters);
});
return citiesAndCounters;
} else {
throw Exception('Failed to fetch city counter detail');
}
}
In the above example, the json.decode function is used to decode the JSON data into a map. Then, the success list is accessed using the key responseBody.success. A new list, citiesAndCounters, is initialized to store the city and counter data.
A forEach loop is used to iterate over each object in the success list. For each object, a new map is created with the city and counters values, and added to the citiesAndCounters list.
Finally, the citiesAndCounters list is returned as the result.
You can then use this function to retrieve the city and counter data as an array, and use it to populate your UI.
To know more, join our Flutter Course today.