Hadi Khan
Hadi Khan

Reputation: 124

How to use http interceptor in a flutter project?

I have to add header to all my Api's. I was told to use http interceptor for that. But i am not able to understand how to do it as i am new to flutter. Can anyone help me with example?

Upvotes: 5

Views: 9972

Answers (1)

Michael Soliman
Michael Soliman

Reputation: 2788

you can use http_interceptor. it works as follows,

first you create your interceptor by implementing InterceptorContract

class MyInterceptor implements InterceptorContract {
  @override
  Future<RequestData> interceptRequest({RequestData data}) async {
    try {
      data.headers["Content-Type"] = "application/json";
    } catch (e) {
      print(e);
    }
    return data;
  }

  @override
  Future<ResponseData> interceptResponse({ResponseData data}) async => data;
}

then create a client and inject this interceptor in it

Client _client = InterceptedClient.build(interceptors: [
      MyInterceptor(),
  ]);

You can add multiple interceptors to the same client, say you want one to refresh the token, one to add/change headers, so it will be something like this:

Client _client = InterceptedClient.build(interceptors: [
      RefreshTokenInterceptor(),
      ContentTypeInterceptor(),
      /// etc
  ]);

note that every interceptor must implement the InterceptorContract

Now anytime you use this client, the request will be intercepted and headers will be added to it. You can make this client a singleton to use the same instance across the app like this

class HttpClient {
Client _client;
static void _initClient() {
    if (_client == null) {
      _client = InterceptedClient.build(
        interceptors: [MyInterceptor()],
      );
    }
  }

  /// implement http request with this client
}

Upvotes: 9

Related Questions