<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Saurabh Detharia on Medium]]></title>
        <description><![CDATA[Stories by Saurabh Detharia on Medium]]></description>
        <link>https://medium.com/@saurabh.detharia?source=rss-3b6d83815d4a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DW4BdiAFXIvX4dSnxEIcKQ.png</url>
            <title>Stories by Saurabh Detharia on Medium</title>
            <link>https://medium.com/@saurabh.detharia?source=rss-3b6d83815d4a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 02:50:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saurabh.detharia/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Auto Refreshing Auth Tokens in Flutter]]></title>
            <link>https://medium.com/simform-engineering/auto-refreshing-auth-tokens-in-flutter-251908f32488?source=rss-3b6d83815d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/251908f32488</guid>
            <category><![CDATA[dios]]></category>
            <category><![CDATA[auth-token]]></category>
            <category><![CDATA[interceptors]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[refresh-token]]></category>
            <dc:creator><![CDATA[Saurabh Detharia]]></dc:creator>
            <pubDate>Mon, 19 May 2025 05:57:10 GMT</pubDate>
            <atom:updated>2025-05-19T05:57:10.675Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide on auth tokens, their roles, and automatically refreshing them in Flutter.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OW8oAeEJnjQye4tvDNlafg.png" /></figure><p>Most modern apps rely on network communication to interact with a server, whether it’s fetching data, uploading information, or handling other backend operations. To manage these interactions efficiently and keep track of user activity, many apps use token-based authentication. It not only helps safeguard sensitive information but also prevents unauthorised access. Let’s take a closer look at what token-based authentication is.</p><h3><strong>What is Token-Based Authentication?</strong></h3><p>After a user’s identity is successfully verified, the server issues an encrypted, machine-generated unique token, known as an <strong>auth token</strong>. During the network communication, this token allows the user to access resources without needing to repeatedly enter their credentials. These tokens are typically valid for a limited period; once they are expired, a new token must be generated to continue secure access.</p><p>Let’s quickly go over the different types of authentication tokens.</p><h4>Types of Tokens:</h4><h3>1. Access Tokens</h3><p>Access tokens are short-lived tokens used to authorize access to specific resources on the server. Once the user logs in, the server issues an access token, which the client then includes in the headers of API requests to authenticate itself. They usually have a short expiration time to minimise security risks. Typically these are included in the Authorization header (e.g., Bearer &lt;token&gt;).</p><h3>2. Refresh Tokens</h3><p>Refresh tokens are used to obtain a new access tokens without requiring the user to re-authenticate. They are issued alongside the access token during login and are usually longer-lived. When the access token expires, the refresh token can be sent to the server to get a new access token.</p><h3>3. ID Tokens</h3><p>ID tokens are primarily used in authentication flows (especially with OpenID Connect) to convey information about the user. Unlike access tokens, which are meant for authorization, ID tokens contain user identity data like username, email, and profile information. Typically these tokens are formatted as a JSON Web Token (JWT).</p><h3>4. Custom Tokens</h3><p>Custom tokens are manually created tokens often used in systems requiring custom authentication flows, like Firebase custom authentication. They allow backend servers to define a user’s identity in their own way before issuing an authentication token.</p><h3><strong>Workflow of Access Token and Refresh Token</strong></h3><p>When implementing token-based authentication, access tokens are issued with a limited lifespan for security reasons. When the access token expires, the server responds with an “Unauthorised Access” (typically a 401) error. Instead of asking the user to log in again, the client uses the <strong>refresh token</strong> to request a new access token. Once the new access token is obtained, all the pending API requests can then be <strong>retried automatically</strong> using the refreshed token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*NzpOCBEBaD1p28Pry-MRgA.png" /></figure><h3>Handling Auto-Refreshing Auth Tokens Using Dio in Flutter</h3><p>To get started with Dio for handling network requests and token management, first, add the <strong>Dio</strong> package to your Flutter project.</p><p>Open your pubspec.yaml file and add the following dependency:</p><pre>dependencies:<br>  dio: ^5.4.0  # (Use the latest version available)</pre><h3>Interceptors</h3><p>When working with APIs, instead of manually handling these in every API call, a middleware mechanism is used, called as <strong>Interceptors, </strong>which allows us to globally monitor, modify, or react to requests, responses, and errors.</p><p>Dio includes a built-in Interceptor class, by extending it, we can gain access to three powerful lifecycle hooks:</p><h4>onRequest:</h4><p>This method is triggered <strong>before</strong> the request is sent. It has RequestOptions and RequestInterceptorHandler params.</p><ul><li>RequestOptions contains all details about the request (e.g., method, headers, path).</li><li>RequestInterceptorHandler is used to <strong>proceed</strong>, <strong>modify</strong>, or <strong>cancel</strong> the request.</li></ul><h4>onResponse:</h4><p>Called <strong>after</strong> the response is received but <strong>before</strong> it reaches our API call. It has Response and ResponseInterceptorHandler params.</p><ul><li>Response includes the status code, headers, body, and more.</li><li>ResponseInterceptorHandler allows us to <strong>modify</strong> or <strong>terminate</strong> the response flow.</li></ul><h4>onError:</h4><p>Triggered whenever an error occurs during the request-response cycle. It has DioException and ErrorInterceptorHandler params.</p><ul><li>DioException contains error type, message, and response info.</li><li>ErrorInterceptorHandler allows us to <strong>retry</strong>, <strong>modify</strong>, or <strong>forward</strong> the error.</li></ul><p>Let’s create an interceptor class by extending Dio’s Interceptor class to access it’s methods.</p><pre>import &#39;package:dio/dio.dart&#39;;<br><br>class ApiInterceptor extends Interceptor {<br>  @override<br>  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {<br>    // Modify request before it is sent<br>    print(&#39;➡️ Request: ${options.method} ${options.uri}&#39;);<br>    <br>    // Add auth token to headers<br>    final token = await getAccessToken();<br>    options.headers[&#39;Authorization&#39;] = &#39;Bearer $token&#39;;<br><br>    handler.next(options); // Continue with the request<br>  }<br><br>  @override<br>  void onResponse(Response response, ResponseInterceptorHandler handler) {<br>    // Intercept successful responses<br>    print(&#39;✅ Response: ${response.statusCode} ${response.requestOptions.uri}&#39;);<br>    <br>    handler.next(response); // Continue with the response<br>  }<br><br>  @override<br>  void onError(DioException err, ErrorInterceptorHandler handler) {<br>    // Handle errors like token expiration or network issues<br>    print(&#39;❌ Error: ${err.response?.statusCode} - ${err.message}&#39;);<br><br>    // Example: Handle 401 Unauthorized (token expired)<br>    if (err.response?.statusCode == 401) {<br>      // Implement our token refresh logic here<br>      // and retry the failed request if needed<br>    }<br><br>    handler.next(err); // Forward the error<br>  }<br>}</pre><p>Now let’s register our interceptor with Dio.</p><pre>final dio = Dio();<br>dio.interceptors.add(ApiInterceptor());</pre><p>This setup is now ready to handle token logic, logging, or any custom behaviour you want globally for all HTTP requests. So, now let’s see how to handle token expiration with refresh token using interceptor.</p><p>To handle token expiration, first we will need to identify when token expires. For this, we’ll use the onError method inside our interceptor (ApiInterceptor) class.</p><p>When an access token expires, the server typically responds with a 401 Unauthorized status code. Therefore, in the onError callback, we can check this status using the DioException&#39;s response object.</p><p>If the statusCode is 401, it means the token is no longer valid, and we can trigger the <strong>token refresh flow</strong>. For rest of the errors (e.g., 400, 404, 500), we&#39;ll simply forward the error to the original request by calling handler.next(err).</p><pre>@override<br>void onError(DioException err, ErrorInterceptorHandler handler) {<br>  if (err.response?.statusCode == 401) {<br>    // Token expired — trigger refresh logic here<br>    print(&#39;🔁 Access token expired. Attempting to refresh...&#39;);<br>    // We can now call our refreshToken() logic<br>  } else {<br>    // Forward all other errors<br>    handler.next(err);<br>  }<br>}</pre><p>This gives us a central place to catch token expiration errors and respond with a refresh strategy.</p><h3>Auto Refreshing Tokens</h3><p>When multiple API calls are made in parallel and the <strong>access token has expired</strong>, all of them may fail at once with the same error — usually a 401 Unauthorized. Without proper handling, this could result in:</p><ul><li>Multiple refresh token requests being fired in parallel</li><li>Redundant API failures</li><li>A broken user experience (e.g., logging the user out unnecessarily)</li></ul><p>Now, let’s understand if multiple API requests are made at the same time and when the access token expires, how it should be handled ideally.</p><p>In such scenarios, as soon as the first request fails due to an expired token, the app should trigger a <strong>single token refresh</strong> process. While this refresh is in progress, all other API requests that also fail due to the expired token should be <strong>queued</strong> (or moved to a pending list). This prevents multiple refresh calls from being triggered simultaneously and ensures a smooth and efficient user experience.</p><p>So, to ensure a seamless user experience, we should follow these steps to ensure proper error handling in case of parallel API calls.</p><ol><li><strong>Intercept all failed requests</strong> caused by token expiry.</li><li><strong>Queue</strong> them as <em>pending requests</em>.</li><li><strong>Refresh the token only once</strong>, on the first failed request.</li><li>After the new token is received, <strong>Retry all pending requests</strong> using the new token and clear the pending queue.</li></ol><p>Now let’s see how to implement the discussed flow.</p><p>We can manage this by creating a <strong>map (or list)</strong> to store failed requests along with their DioException and ErrorInterceptorHandler instances. This acts as a retry queue.</p><p>To <strong>prevent multiple refresh calls</strong>, we will use a boolean flag like isRefreshing. Now only the first 401 triggers the refresh flow; the rest just wait in the queue.</p><pre>class ApiInterceptor extends Interceptor {<br>  bool isRefreshing = false;<br>  final List&lt;PendingRequest&gt; pendingRequests = [];<br><br>  @override<br>  void onError(DioException error, ErrorInterceptorHandler handler) async {<br>    // Verify the 401 Unauthorized (token expired) error<br>    if (error.response?.statusCode == 401) {<br>      final request = PendingRequest(error, handler);<br><br>      // Add failed request to queue<br>      pendingRequests.add(request);<br><br>      // For the first failed request, this<br>      // will allow to proceed further.<br>      if (!isRefreshing) {<br>        // Update flag to prevent multiple refreshToken call<br>        isRefreshing = true;<br><br>        try {<br>          // Refresh token and get new token pair<br>          final newToken = await refreshToken();<br><br>          // Save new token pair<br>          await saveAccessToken(newToken);<br><br>          // Retry all pending requests<br>          for (final pending in pendingRequests) {<br>            <br>            // Update header with new access token<br>            final options = pending.error.requestOptions;<br>            options.headers[&#39;Authorization&#39;] = &#39;Bearer $newToken&#39;;<br>            <br>            // Retry request<br>            final response = await dio.fetch(options);<br>            <br>            // Resend response from where request was called <br>            pending.handler.resolve(response);<br>          }<br>        } catch (e) {<br>          // Failed to refresh token<br>          // Send error from where requests were called <br>          for (final pending in pendingRequests) {<br>            pending.handler.reject(error);<br>          }<br>        } finally {<br>          // Remove all requests from the <br>          // queue and reset flag<br>          pendingRequests.clear();<br>          isRefreshing = false;<br>        }<br>      }<br>    } else {<br>      handler.next(error);<br>    }<br>  }<br>}<br><br>class PendingRequest {<br>  const PendingRequest(<br>    this.error,<br>    this.handler,<br>  );<br><br>  final DioException error;<br>  final ErrorInterceptorHandler handler;<br>}</pre><p>This pattern ensures only one refresh request is active at a time and all failed requests are retried once the new token is available.</p><h3>Conclusion</h3><p>In this article, we explored the importance of authentication tokens, their various types, and how to implement a robust token refresh mechanism using <strong>Dio interceptors</strong> in Flutter.</p><p>By leveraging interceptors, our app can:</p><ul><li>Seamlessly handle token expiration</li><li>Refresh access tokens without user interruption</li><li>Queue and retry failed API calls automatically</li></ul><p>This not only simplifies our network layer but also delivers a <strong>smoother, more reliable user experience</strong>, especially in scenarios involving multiple parallel API calls.</p><blockquote><strong><em>For more updates on the latest tools and technologies, follow the </em></strong><a href="https://medium.com/simform-engineering"><strong><em>Simform Engineering</em></strong></a><strong><em> blog.</em></strong></blockquote><blockquote><strong><em>Follow us: </em></strong><a href="https://twitter.com/simform"><strong><em>Twitter</em></strong></a><strong><em> | </em></strong><a href="https://www.linkedin.com/company/simform/"><strong><em>LinkedIn</em></strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=251908f32488" width="1" height="1" alt=""><hr><p><a href="https://medium.com/simform-engineering/auto-refreshing-auth-tokens-in-flutter-251908f32488">Auto Refreshing Auth Tokens in Flutter</a> was originally published in <a href="https://medium.com/simform-engineering">Simform Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Developer’s perspective for Flutter]]></title>
            <link>https://medium.com/@saurabh.detharia/android-developers-perspective-for-flutter-da4120cf20dd?source=rss-3b6d83815d4a------2</link>
            <guid isPermaLink="false">https://medium.com/p/da4120cf20dd</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Saurabh Detharia]]></dc:creator>
            <pubDate>Mon, 16 Aug 2021 05:27:00 GMT</pubDate>
            <atom:updated>2021-08-16T05:27:00.818Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uYAXcfO8bYzSvv1gRvSMw.png" /></figure><p>Google has introduced Flutter as a Cross-platform framework, by which the developers can run on both platforms with the same look and feel, single codebase, hot restart / reload and much more. Attractive UI and Animations have always attracted developers and clients as well. Additionally, web app and desktop support using the same codebase, what to say!</p><p>I started my journey with Flutter, by directly jumping into a live project, without having much knowledge about syntaxes, much about widgets or structures. Just converted design to words for Google and learnt Flutter, though I was working with Android previously and therefore, I compared widgets with Android layout components. Later on, I got the idea that it is not the same, as the state was never in the picture, in my Android story. Let’s see how Flutter is relatable with Android and as an Android developer what can be your perspectives.</p><p>If we talk about UI the components, Flutter calls widgets and Android call layout and much more widgets can be related to Android layouts. The properties of widgets also can be easily understood if you have good knowledge of Android layouts. With responsive or adaptive designs, you can run the same code base to web and mobile. What you will miss here is layout xml files, because here, view and logic will be in a single file. Not to worry, either you will be habituated with it or you will code according to a structure. 😉 Say Goodbye to lengthy codes for round shapes, full-screen themes and animations. Yes! you heard right, you won’t need a lengthy code for it.</p><p>Flutter will test your little passion, little a bit of practice and passion for few days and you will start creating apps as you want. But as the coin has two sides, let’s see the backside of Flutter in comparison to Android. First, more functionalities, more packages. Another is if you want to implement complex functionalities, you might need to take help from Android. Last I would say, it will run over Android, it will take some buffers.</p><p><strong>Pros:<br></strong>1. Single codebase, multiple platforms<br>2. Attractive UI and full of easy animations<br>3. Hot reload and hot restart<br>4. Open source<br>5. Well documented and great communities</p><p><strong>Cons:<br></strong>1. May problematic for complex apps<br>2. Under development<br>3. More depends on packages<br>4. Occupies more space than native</p><p>In simpler words, the Flutter is best when you have simple yet attractive apps and Android is ever!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da4120cf20dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>