Flutter HTTP Interceptor for Refresh Token with http_interceptor

Muhammad Asaif
2 min readApr 22, 2022

Hi, there. Sometimes we need to update the token as it is expired on the backend due to some security reasons, but we do not want our users to face any hassle while using the app. For this, we need to retry our request silently when it gives us 401 unauthorized. This can also be achievable by Interceptor. If you are using Dio for network calls then Dio has covered it. But if you are using a simple flutter HTTP plugin then this article is going to help you implement interceptor with HTTP and you can easily refresh your token on 401 and retry your request with an updated token.

Plugin Used:

Read comments carefully, I have tried my best to put all code in one picture so you can understand it better.

  1. Authorization Interceptor
  2. Retry Policy
  3. Your APIs base class is where you do your network layer part. Use client with the interceptor.
  4. The last code is just for knowledge to those who try to understand the refresh part of the token, and how to get and set the refresh token in local data.

Happy fluttering. Clap if you like it. Comment your suggestions. Subscribe for more.

--

--