Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Global Http Interceptor

Tags:

flutter

dart

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!

like image 849
Ryan Paing Avatar asked Mar 18 '20 18:03

Ryan Paing


3 Answers

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.

like image 62
Felipe Medeiros B. Avatar answered Sep 25 '22 02:09

Felipe Medeiros B.


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
 ],
);
like image 26
GJJ2019 Avatar answered Sep 21 '22 02:09

GJJ2019


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;
}

}
like image 20
sujith s Avatar answered Sep 24 '22 02:09

sujith s