onRequest method
Intercepts outgoing requests and attaches the authentication token.
If a token is available, it is added to the request headers with
the key defined in the interceptor configuration (Authorization
by default).
If a callback for token request handling is defined, it is triggered.
Usage Example:
dio.interceptors.add(TokenInterceptor());
Implementation
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
var tokenHeader = options.headers.keys.where((e) => e.toLowerCase() == _tokenKey.toLowerCase());
var hasTokenKey = tokenHeader.isNotEmpty;
// Check if a token exists and append it to the request headers
if (VenturoApiManager.getToken.isNotEmpty && !hasTokenKey) {
options.headers.addAll(<String, dynamic>{
_tokenKey: "Bearer ${VenturoApiManager.getToken}",
});
}
// Trigger the configured onRequestToken callback if available
if (config?.onRequestToken != null) config!.onRequestToken!();
// Proceed with the request
super.onRequest(options, handler);
}