Interceptors are added to a Dio instance in a queue (FIFO). They allow you to perform unified operations before a request is sent, after a response is received, or when an error occurs.
You can use InterceptorsWrapper to implement these hooks. Within an interceptor, you can:
- Resolve: Return a custom
Response to bypass the actual network call. - Reject: Return a
DioException to trigger an error in the caller's catchError block. - Next: Pass the request/response to the next interceptor in the queue.
dio.interceptors.add(
InterceptorsWrapper(
onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
// To complete request with custom data:
// return handler.resolve(Response(requestOptions: options, data: 'fake data'));
return handler.next(options);
},
onResponse: (Response response, ResponseInterceptorHandler handler) {
// To terminate and trigger error:
// return handler.reject(DioException(...));
return handler.next(response);
},
onError: (DioException error, ErrorInterceptorHandler handler) {
return handler.next(error);
},
),
);