Mastering HTTP Requests in Flutter with Dio Package

Abdou Aziz NDAO
4 min readFeb 21, 2023

--

Photo by Timothy Hales Bennett on Unsplash

Introduction

Dio is an HTTP client for Dart that makes it easy to work with APIs and perform HTTP requests. It is built on top of the Dart HttpClient, with added features that make it more powerful and flexible.

In this tutorial, we will explore how to use Dio in a Flutter application and take a look at some of its features.

Step 1: Installing Dio

To use Dio in a Flutter application, you need to add the package to your project. You can do this by adding the following line to your pubspec.yaml file:

dependencies:
dio: ^5.4.0

After adding the package to your project, run flutter pub get to install it.

Step 2: Making HTTP Requests with Dio

The Dio package provides an easy-to-use API for making HTTP requests. To make a GET request, for example, you can use the dio.get() method. Here is an example of how to make a GET request to the JSONPlaceholder API:

import 'package:dio/dio.dart';

...
final dio = Dio();
final response = await dio.get('https://jsonplaceholder.typicode.com/todos/1');
print(response.data);
...

In the code above, we create an instance of the Dio class and use it to make a GET request to the JSONPlaceholder API. The response is then printed to the console.

You can also make other types of HTTP requests, such as POST, PUT, and DELETE. Here is an example of how to make a POST request:

import 'package:dio/dio.dart';

...
final dio = Dio();
final response = await dio.post('https://jsonplaceholder.typicode.com/posts',
data: {
'title': 'My post',
'body': 'This is my post content',
'userId': 1,
},
);
print(response.data);
...

In the code above, we use the dio.post() method to make a POST request to the JSONPlaceholder API. The data we send with the request is a JSON object containing the title, body, and userId of the post we want to create.

Step 3: Interceptors

Dio also provides interceptors, which allow you to modify requests and responses before they are sent or received. Interceptors can be used for a variety of purposes, such as adding headers to requests, handling errors, or logging network traffic.

Here is an example of how to add an interceptor to a Dio instance:

import 'package:dio/dio.dart';

...

final dio = Dio();
dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) {
// Add a custom header to the request
options.headers['Authorization'] = 'Bearer my_token';
return handler.next(options);
},
),
);
final response = await dio.get('https://jsonplaceholder.typicode.com/todos/1');
print(response.data);
...

In the code above, we add an interceptor to the Dio instance that adds a custom Authorization header to every request. The onRequest callback is called before the request is sent, and the onResponse callback is called after the response is received. The onError callback is called if there is an error.

Step 4: Cancellation

Dio also provides cancellation tokens that allow you to cancel requests that are no longer needed. This can be useful in situations where you need to abort a request that is taking too long or is no longer relevant.

Here is an example of how to use a cancellation token:

import 'package:dio/dio.dart';

...
final dio = Dio();
final cancelToken = CancelToken();
final response = await dio.get('https://jsonplaceholder.typicode.com/todos/1',
cancelToken: cancelToken,
);
print(response.data);
// Cancel the request
cancelToken.cancel('Request cancelled');
...

In the code above, we create a CancelToken and pass it to the dio.get() method. If we decide to cancel the request, we can call the cancel() method on the CancelToken object.

Step 5: Error Handling

Dio provides a convenient way to handle errors that may occur when making HTTP requests. You can use the dio.on method to register an error handler that will be called whenever an error occurs.

Here is an example of how to handle errors:

import 'package:dio/dio.dart';

...
final dio = Dio();
dio.on(DioError, (error, handler) {
print('Request failed with error: ${error.message}');
return handler.next(error);
});
final response = await dio.get('https://jsonplaceholder.typicode.com/todos/999');
print(response.data);
...

In the code above, we register an error handler that is called whenever a DioError occurs. The error message is printed to the console, and the error is passed on to the next error handler.

Conclusion

In this tutorial, we have explored the Dio package and how to use it to make HTTP requests in a Flutter application. We covered the basics of making HTTP requests, using interceptors, cancelling requests, and error handling.

Dio is a powerful and flexible package that makes it easy to work with APIs in Dart. It offers many features and options that allow you to customize your HTTP requests and handle errors effectively. I hope this tutorial has been helpful, and I encourage you to explore Dio further in your own projects.

--

--