How to call nested json data using API in flutter?

CodeWithFlutter
2 Min Read

In Flutter, you can use the http package to make API calls and retrieve data in JSON format. To access nested JSON data, you can use the indexing operator ([]) to access the properties of nested objects.

Here’s an example of how to call a nested JSON API and access its data in Flutter:

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<void> fetchData() async {
  final response = await http.get('https://your-api-endpoint.com/data');
  if (response.statusCode == 200) {
    Map<String, dynamic> data = json.decode(response.body);
    // Access a property of a nested object
    String nestedProperty = data['nestedObject']['property'];
    print(nestedProperty);
  } else {
    throw Exception('Failed to fetch data');
  }
}

void main() {
  fetchData();
}

In this example, the fetchData function uses the http.get method to retrieve the data from the API endpoint. The json.decode method is then used to parse the JSON string into a Map object, allowing you to access the properties of the nested objects using the indexing operator.

Note that this is just an example and may not exactly match the structure of the API you’re working with. You’ll need to adapt the code to match the structure of your specific API and data.

Share this Article
Leave a comment