Search code examples
flutterinterceptordio

Dio: How to add multiple interceptors?


I need to add multiple interceptors to my Dio object and I don't know how?

I've already added a interceptor in order to add headers to requests. This is my current Dio Object :

Provider(create: (BuildContext context) =>
Dio(BaseOptions(baseUrl: ApiEndPoints.baseURL))
..interceptors.add(InterceptorsWrapper(
  onRequest: (options, handler) {
    final accessToken = accessTokenChangeNotifier.value;
    if (accessToken != null && accessToken.isNotEmpty) {
      options.headers['Authorization'] = accessToken;
    }
    options.headers[HttpHeaders.contentTypeHeader] = "application/json";
    handler.next(options);
  } ,
  onError: (error , handler) async{
    try {
      handler.resolve(error.response!);
    } catch (e) {
      return handler.next(error);
    }
  },
)
)),

Now I want to add another logger interceptor named curl_logger_dio_interceptor: According to it's document I should add this interceptor like this:

_dio = Dio();
_dio.interceptors.add(CurlLoggerDioInterceptor());

But I've already added a interceptor to my Dio and this piece of code doesn't work for me. Probably I should use _dio.interceptors.addAll method but I don't know how to handle this.


Solution

  • You can use add function to add more interceptors with .. continuation.

    Provider(create: (BuildContext context) =>
    Dio(BaseOptions(baseUrl: ApiEndPoints.baseURL))
    ..interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        final accessToken = accessTokenChangeNotifier.value;
        if (accessToken != null && accessToken.isNotEmpty) {
          options.headers['Authorization'] = accessToken;
        }
        options.headers[HttpHeaders.contentTypeHeader] = "application/json";
        handler.next(options);
      } ,
      onError: (error , handler) async{
        try {
          handler.resolve(error.response!);
        } catch (e) {
          return handler.next(error);
        }
      },
    )
    )..interceptors.add(CurlLoggerDioInterceptor())),