Implement Interceptors to modify requests and responses
mainInterceptors allow you to observe, modify, or handle errors for every request and response. You can implement the Interceptor class or use the simpler SimpleInterceptor.
Interceptor Methods
beforeRequest: Modify theHttpRequestbefore it is sent.afterResponse: Process theHttpResponseafter it is received.onError: Handle exceptions occurring during the request lifecycle.
Termination Methods
When returning an InterceptorResult, use:
Interceptor.next(): Continue to the next interceptor.Interceptor.stop(): Halt the interceptor chain.Interceptor.resolve(): Resolve the request immediately with a provided response.throw RhttpException: Throw an exception (preserves stack trace).
class TestInterceptor extends Interceptor {
@override
Future<InterceptorResult<HttpRequest>> beforeRequest(
HttpRequest request,
) async {
return Interceptor.next(request.addHeader(
name: HttpHeaderName.accept,
value: 'application/json',
));
}
@override
Future<InterceptorResult<HttpResponse>> afterResponse(
HttpResponse response,
) async {
return Interceptor.next();
}
@override
Future<InterceptorResult<RhttpException>> onError(
RhttpException exception,
) async {
return Interceptor.next();
}
}