JSON parsing using dio in Flutter

Bobby K Bose
4 min readDec 26, 2022

--

Let’s get straight to the point without any Unnecessary Introduction :-

To parse JSON in Flutter using the dio package and a real URL, you can use the Response.data property of a Response object and pass it to the jsonDecode function from the dart:convert library.

Here is an example that parses the JSON response from the “NovelCOVID” API (https://corona.lmao.ninja/v2/countries), which provides information about the number of confirmed cases, deaths, and recoveries for various countries:

import 'package:dio/dio.dart';
import 'dart:convert';

Future<void> getCountryData() async {
// Make a GET request to the API
Response response = await Dio().get("https://corona.lmao.ninja/v2/countries");

// Parse the JSON
List<dynamic> data = jsonDecode(response.data);

// Access the values in the parsed JSON
for (var country in data) {
print(country['country']);
print(country['cases']);
print(country['deaths']);
print(country['recovered']);
}
}

This will make a GET request to the API and parse the JSON response into a list of maps, where each map represents a country. You can then access the values for each country using the keys of the JSON object (e.g., country, cases, deaths, and recovered).

Note that you will need to import the dio package and the jsonDecode function from dart:convert in order to use this code.

Now a more detailed explanation over here :-

To read a public API and understand the data it returns, you can follow these steps:

  1. Find the API documentation: Look for documentation or an API reference that explains the structure of the API and the data it returns. This will typically include information about the available endpoints (URLs that you can make requests to), the parameters that you can use in your requests, and the format of the responses.
  2. Make a request to the API: Use a tool like curl or a library like dio in your programming language of choice to make a request to the API. This will typically involve constructing a URL with the appropriate endpoint and any necessary parameters, and then making an HTTP GET request to that URL.
  3. Inspect the response: Look at the response you receive from the API. This will typically be in the form of a JSON object or an array of JSON objects. Inspect the structure of the response and try to understand how the data is organized and what each piece of data represents.
  4. Parse the response: Use a JSON parsing library or function to parse the response into a more usable format, such as a list of dictionaries in Python or a Map<String, dynamic> in Dart. This will make it easier to access and manipulate the data.
  5. Access and use the data: Once you have the data in a usable format, you can access and use it in your code. For example, you might loop through the data and display it on a webpage, or you might use it to make calculations or decisions in your application.

Here is an example of how you might make a request to the “NovelCOVID” API (https://corona.lmao.ninja/v2/countries) using dio in Flutter and parse the JSON response:

import 'package:dio/dio.dart';
import 'dart:convert';

Future<void> getCountryData() async {
// Make a GET request to the API
Response response = await Dio().get("https://corona.lmao.ninja/v2/countries");

// Parse the JSON
List<dynamic> data = jsonDecode(response.data);

// Access the values in the parsed JSON
for (var country in data) {
print(country['country']);
print(country['cases']);
print(country['deaths']);
print(country['recovered']);
}
}

This will make a GET request to the API and parse the JSON response into a list of maps, where each map represents a country. You can then access the values for each country using the keys of the JSON object (e.g., country, cases, deaths, and recovered).

dio is a powerful HTTP client library for Flutter and Dart, with support for interceptors, global configuration, and more.To install dio in your Flutter project, add it to your pubspec.yaml file as a dependency:

dependencies:
dio: ^3.2.2

Then, run flutter pub get to install the package.

To use dio in your code, you can import it and create an instance of the Dio class. The Dio class has several constructors that allow you to configure the behavior of the HTTP client.

Here are some of the main constructors for the Dio class:

  • Dio([BaseOptions options]): This constructor creates a new Dio instance with the given options. The options parameter is an instance of the BaseOptions class, which contains a number of properties that you can use to configure the behavior of the HTTP client. Some of the main properties of BaseOptions are:
  • baseUrl: The base URL to use for all requests made by this Dio instance.
  • connectTimeout: The timeout for establishing a connection, in milliseconds.
  • receiveTimeout: The timeout for receiving a response, in milliseconds.
  • headers: A map of HTTP headers to send with every request made by this Dio instance.
  • contentType: The content type of the request.

Here is an example of how you might use the Dio constructor to create a new Dio instance with custom options:

import 'package:dio/dio.dart';

final dio = Dio(BaseOptions(
baseUrl: 'https://example.com',
connectTimeout: 5000,
receiveTimeout: 3000,
headers: {'Authorization': 'Bearer 123456'},
contentType: 'application/json',
));

This creates a new Dio instance that will use the given base URL, timeouts, headers, and content type for all requests made with this instance. You can then use the dio instance to make HTTP requests, like this:

// Make a GET request
Response response = await dio.get('/users');
// Make a POST request
Response response = await dio.post('/users', data: {'name': 'John'});
// Make a PUT request
Response response = await dio.put('/users/1', data: {'name': 'Jane'});
// Make a DELETE request
Response response = await dio.delete('/users/1');

--

--

Bobby K Bose

Python | Flask | Django | Data Science | ML | Flutter | e-Certified Penetration Tester