Flutter: Interceptors in Dio

Utsav Ghimire
3 min readNov 11, 2022

--

What are interceptors?

Interceptors are the middleware that allows changing the behavior of the method without modifying the source code.

In the Dio, the interceptors are the layer between the client and server that modifies the requests and responses intercepting the HTTP request.

Is it essential to use interceptors?

Let us think of a simple app that functions well without errors or the user authentication is not that important. So obviously, we don’t need interceptors here.

But is every application as simple as that?

Of course not.

As the requirement increases, user authentication, error handling, dynamic request header, and caching response are necessary.

The API response is complex; we must log it on every request and response.

Here, interceptors play a vital role and prevent us from repeating the code for each request or response.

Thankfully, for logging requests and responses, dio provides LogInterceptor.

Let us log our request and response.

You can see the logs in your console

LogInterceptor is the interceptor for logging the requests and responses.

But can we make our own interceptors?

Yes, of course.

Let us make our own interceptor that adds authorization in every requests.

The above interceptor adds the token in every request. If the backend developer warns you not to send the token in every request or navigates the user to the login screen if the token is expired.

We have onResponse and onError methods available in the Interceptor class, and we can override them.

onResponse callback is executed on success.

onError callback is executed on failure.

The available methods on the handler.

Resolve: The resolve callback returns a response directly without executing other interceptors.

Reject: The reject callback completes the request without executing other interceptors.

Next: The resolve callback continues to call the next interceptors.

From now on, whenever you are trying to make an HTTP call, keep in mind to make the most out of interceptors.

Interceptors can be used to cache the response so that we can show the old response whenever there’s a network error.

I will add a GitHub repository that demonstrates the use of interceptors for caching the responses, handling errors, and various other request manipulations.

So stay tuned and make sure to connect with me on Linkedin and Github

--

--