I would like to know if it is possible to have a global HTTP interceptor to attach token in header for all requests in Flutter? I've searched a lot and couldn't find any information as where and how to set it up as globally. Thanks a lot!
You can extend BaseClient and override send(BaseRequest request)
:
class CustomClient extends BaseClient {
static Map<String, String> _getHeaders() {
return {
'Authentication': 'c7fabcDefG04075ec6ce0',
};
}
@override
Future<StreamedResponse> send(BaseRequest request) async {
request.headers.addAll(_getHeaders());
return request.send();
}
}
In the above example the 'Authentication': 'c7fabcDefG04075ec6ce0'
is hardcoded and not encrypted which you should never do.
Using dio package u can do that :
Dio dio = Dio(BaseOptions(
connectTimeout: 30000,
baseUrl: 'your api',
responseType: ResponseType.json,
contentType: ContentType.json.toString(),
))
..interceptors.addAll(
[
InterceptorsWrapper(onRequest: (RequestOptions requestOptions) {
dio.interceptors.requestLock.lock();
String token = ShareP.sharedPreferences.getString('token');
if (token != null) {
dio.options.headers[HttpHeaders.authorizationHeader] =
'Bearer ' + token;
}
dio.interceptors.requestLock.unlock();
return requestOptions;
}),
// other interceptor
],
);
Flutter provides http_interceptor.dart package.
Sample
class LoggingInterceptor implements InterceptorContract {
@override
Future<RequestData> interceptRequest({RequestData data}) async {
print(data);
return data;
}
@override
Future<ResponseData> interceptResponse({ResponseData data}) async {
print(data);
return data;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With