DEV Community

CR Poudyal
CR Poudyal

Posted on

Dio Interceptors in Flutter

Medium Articles

Dio interceptors are a feature of the Dio library in Flutter that allow you to intercept and modify HTTP requests and responses. This can be useful for a variety of purposes, such as logging, debugging, authentication, and caching.

To use interceptors with Dio, you first need to create an instance of the Dio class and then add your interceptors to the interceptors list. For example, suppose you want to create an interceptor that logs all requests and responses:

var dio = Dio();

dio.interceptors.add(InterceptorsWrapper(
  onRequest: (RequestOptions options) {
    print('Request: ${options.method} ${options.path}');
    return options;
  },
  onResponse: (Response response) {
    print('Response: ${response.statusCode}');
    return response;
  },
  onError: (DioError e) {
    print('Error: ${e.message}');
    return e;
  },
));
Enter fullscreen mode Exit fullscreen mode

Here, an instance of the Dio class is created and then an interceptor is added to the interceptors list. The interceptor has three callback functions: onRequest(), onResponse(), and onError(). These callback functions are called whenever a request is made, a response is received, or an error occurs, respectively. In this example, the callback functions simply log the request and response information.

Once you have added your interceptors, you can use the Dio instance to make HTTP requests as usual. The interceptors will automatically be applied to each request and response.

In general, Dio interceptors are a powerful and flexible tool for modifying HTTP requests and responses in Flutter. They can be used for a variety of purposes, such as logging, debugging, authentication, and caching.

Top comments (0)