<?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 João Davi Franco on Medium]]></title>
        <description><![CDATA[Stories by João Davi Franco on Medium]]></description>
        <link>https://medium.com/@jdavifranco?source=rss-730922167b5c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lFuWxKb_nV4vOWmmgwNmaA.jpeg</url>
            <title>Stories by João Davi Franco on Medium</title>
            <link>https://medium.com/@jdavifranco?source=rss-730922167b5c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:50:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jdavifranco/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[How to Implement a Retry Interceptor in Flutter with Dio]]></title>
            <link>https://medium.com/@jdavifranco/how-to-implement-a-retry-interceptor-in-flutter-with-dio-26ab3c157483?source=rss-730922167b5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/26ab3c157483</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[João Davi Franco]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 04:41:24 GMT</pubDate>
            <atom:updated>2025-03-08T16:43:25.815Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s learn how to implement a retry interceptor in Flutter using the Dio library to enhance the resilience of your network requests.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i8czVLvv4WyoIfac" /><figcaption>Photo by <a href="https://unsplash.com/@roketpik?utm_source=medium&amp;utm_medium=referral">Artur Shamsutdinov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. What are Interceptors?</h3><p>In an HTTP client, an interceptor is middleware that sits between your application and the server. It allows you to intercept and modify outgoing HTTP requests and incoming responses before they reach your application code. This enables you to perform actions like:</p><ul><li>Adding headers</li><li>Handling errors</li><li>Logging requests</li><li>Performing authentication checks</li></ul><p>Interceptors apply this logic consistently across all API calls without requiring repetitive code in each individual request.</p><h3>2. Why Use Interceptors?</h3><p>Interceptors act as middleware, intercepting HTTP requests and responses at key points in their lifecycle. The HttpClient Interceptor architecture offers several benefits:</p><ul><li><strong>Centralized Logic</strong>: Encapsulate cross-cutting concerns like authentication, error handling, and logging in a single place.</li><li><strong>Dynamic Request/Response Modification</strong>: Modify requests and responses programmatically based on application state or server requirements.</li><li><strong>Global Error Recovery Strategies</strong>: Implement consistent error handling and retry mechanisms across your application.</li></ul><p>These capabilities are particularly valuable for applications dealing with APIs where network operations must handle:</p><ul><li>Token-based authentication</li><li>Unreliable network conditions</li><li>Consistent error reporting</li></ul><p>By decoupling network logic from business logic, interceptors align with SOLID principles, promoting maintainable and scalable code.</p><h3>3. How Do Interceptors Work?</h3><p>Interceptors operate in three distinct phases, providing interception points at different stages of the HTTP request/response cycle:</p><h3>Phase 1: onRequest</h3><ul><li><strong>Purpose:</strong> Modify outgoing requests <em>before</em> they are sent to the server.</li><li><strong>Key Operations:<br></strong>– Inject authentication headers (e.g., JWT tokens in the Authorizationheader).<br>– Validate request parameters before sending.<br>– Add API keys or localization headers.<br>– Cancel invalid requests (e.g., requests with missing required fields).</li></ul><h3>Phase 2: onResponse</h3><ul><li><strong>Purpose:</strong> Process successful server responses <em>after</em> they are received but before they are processed by your application.</li><li><strong>Key Operations:<br></strong>– Normalize data formats<br>– Extract metadata from response headers (e.g., pagination tokens, rate limits).</li></ul><h3>Phase 3: onError</h3><ul><li><strong>Purpose:</strong> Handle failed requests and implement error recovery mechanisms.</li><li><strong>Key Operations:<br></strong>– Retry transient failures (e.g., network timeouts, 5xx server<br> errors).<br>– Redirect users to a login screen after session expiration (HTTP 401 Unauthorized).<br>– Log errors to monitoring tools for debugging and analysis.</li></ul><h3>4. How to Implement a Retry Interceptor</h3><p>Now, let’s focus on the main topic: implementing a retry interceptor. Retry interceptors are crucial for automatically managing transient network failures, enhancing application resilience and user experience.</p><h3>4.1. Understanding Retry Strategies: Intelligent Retries</h3><p>Simply retrying every failed request without discrimination can be inefficient and detrimental. Intelligent retry strategies are essential for effective error recovery. These strategies involve:</p><ul><li><strong>Targeting Transient Errors:</strong> Retry only when errors are likely temporary:<br>– Network timeouts (DioExceptionType.connectionTimeout, DioExceptionType.receiveTimeout, DioExceptionType.sendTimeout, DioExceptionType.connectionError).<br>– HTTP 5xx server errors (e.g., 500 Internal Server Error, 503 Service Unavailable).<br>– Application-specific errors indicating transient issues (e.g., rate limit exceeded).</li><li><strong>Avoiding Non-Transient Errors:</strong> Do not retry errors indicating permanent issues or requiring client-side changes:<br>– HTTP 4xx client errors (e.g., 400 Bad Request, 404 Not Found).<br>– Request validation failures.</li><li><strong>Exponential Backoff with Jitter:</strong> Implement increasing delays between retries to avoid overwhelming the server and incorporate randomness (jitter) to prevent retry storms.</li><li><strong>Selective Retries:</strong> Apply retry logic only to specific request types or API endpoints as needed, allowing fine-grained control.</li></ul><p>By implementing these intelligent retry strategies within a Dio interceptor, you can build more resilient and user-friendly Flutter applications.</p><h3>4.2. Retry Interceptor with Dio: Code Implementation</h3><p>Let’s implement a RetryInterceptor in Flutter using Dio, incorporating exponential backoff and selective retries. Here is the Dart code for the RetryInterceptor class:</p><pre>import &#39;dart:async&#39;;<br>import &#39;dart:math&#39;;<br>import &#39;package:dio/dio.dart&#39;;<br><br>import &#39;../models/retry_config.dart&#39;;<br><br>class RetryInterceptor extends Interceptor {<br>  static const retryEnabledKey = &#39;retry_enabled&#39;;<br>  static const retryErrorConditionsKey = &#39;retry_error_conditions&#39;;<br>  RetryInterceptor({<br>    required this.dio,<br>    required this.retryConfig,<br>  });<br>  final Dio dio;<br>  final RetryConfig retryConfig;<br>  @override<br>  Future onError(DioException err, ErrorInterceptorHandler handler) async {<br>    final retryCount = err.requestOptions.retryCount + 1;<br>    if (!err.requestOptions.isRetryEnabled(retryEnabledKey) ||<br>        !_shouldRetry(err, retryCount, retryConfig)) {<br>      return handler.next(err);<br>    }<br><br>    err.requestOptions.retryCount = retryCount;<br>    final delay = _calculateDelay(retryCount);<br>    print(<br>        &#39;Retry attempt: $retryCount, Delay: ${delay.inMilliseconds}ms, Error: ${err.message}&#39;);<br>    if (delay != Duration.zero) {<br>      await Future.delayed(delay);<br>    }<br><br>    try {<br>      final response = await dio.request(<br>        err.requestOptions.path,<br>        options: Options(<br>          method: err.requestOptions.method,<br>          headers: err.requestOptions.headers,<br>          extra: err.requestOptions.extra,<br>        ),<br>        cancelToken: err.requestOptions.cancelToken,<br>        data: err.requestOptions.data,<br>        queryParameters: err.requestOptions.queryParameters,<br>      );<br>      return handler.resolve(response);<br>    } on DioException catch (e) {<br>      return super.onError(e, handler);<br>    } catch (_) {<br>      return handler.reject(err);<br>    }<br>  }<br><br>  Duration _calculateDelay(int retryCount) {<br>    final random = Random();<br>    final jitter = random.nextDouble() * retryConfig.baseDelayInMiliseconds;<br>    final delay = retryConfig.baseDelayInMiliseconds * pow(2, retryCount - 1);<br>    return Duration(milliseconds: (delay + jitter).toInt());<br>  }<br><br>  bool _shouldRetry(<br>      DioException error, int retryCount, RetryConfig retryConfig) {<br>    if (retryCount &gt; retryConfig.maxRetries) {<br>      return false;<br>    }<br><br>    final retryErrorStatusCodes =<br>        error.requestOptions.getRetryErrorStatusCodes(retryErrorConditionsKey);<br>    final isRetryableError = error.response != null &amp;&amp;<br>        retryErrorStatusCodes.contains(error.response?.statusCode);<br><br>    return error.type == DioExceptionType.connectionTimeout ||<br>        error.type == DioExceptionType.receiveTimeout ||<br>        error.type == DioExceptionType.sendTimeout ||<br>        error.type == DioExceptionType.connectionError ||<br>        isRetryableError;<br>  }<br>}<br><br>extension RequestOptionsRetryExtension on RequestOptions {<br>  bool isRetryEnabled(String key) =&gt; (extra[key] as bool?) ?? false;<br>  List&lt;int&gt; getRetryErrorStatusCodes(String key) {<br>    final statusCodes = extra[key] as List&lt;int&gt;?;<br>    return statusCodes ?? [];<br>  }<br><br>  int get retryCount =&gt; (extra[&#39;retryCount&#39;] as int?) ?? 0;<br>  set retryCount(int value) =&gt; extra[&#39;retryCount&#39;] = value;<br>}</pre><h3>4.3. Code Breakdown: Key Components Explained</h3><p>Let’s examine the essential parts of the RetryInterceptor code to quickly understand its functionality:</p><ul><li><strong>RetryInterceptor Class and Constants:</strong> This class is the core of the retry mechanism, extending Dio&#39;s Interceptor. retryEnabledKey and retryErrorConditionsKey are constants used to selectively control retries for individual requests via RequestOptions.extra.</li><li><strong>onError Method: Error Handling and Retry Orchestration:</strong> This is the central method, automatically called by Dio on request errors. It manages the entire retry process:<br> – Retry Check: Verifies if retries are enabled and needed using isRetryEnabled() and _shouldRetry().<br> – Delay Calculation: Calculates delay using _calculateDelay().<br> – Request Re-execution: Re-sends request using dio.request().<br> – Chain Resolution: Handles success or failure.</li><li><strong>_shouldRetry Method: Retry Decision Logic:</strong> This method determines <em>if</em> a retry is necessary by checking retry limits, DioExceptionType, and custom status codes.</li><li><strong>_calculateDelay Method: Retry Delay Strategy:</strong> Implements exponential backoff with jitter for calculating delays.</li><li><strong>RetryConfig:</strong></li></ul><pre>class RetryConfig {<br>  final int maxRetries;<br>  final int baseDelayInMiliseconds;<br><br>  const RetryConfig({<br>    this.maxRetries = 3,<br>    this.baseDelayInMiliseconds = 1000,<br>  });<br>}</pre><ul><li>RetryConfig: Configures retry parameters:</li><li>maxRetries: Maximum retry attempts (default: 3).</li><li>baseDelayInMiliseconds: base delay for exponential backoff (default:1000ms).</li></ul><p>The RetryInterceptor code already supports selective retries using retryEnabledKey and retryErrorConditionsKey in requestOptions.extra. Here&#39;s how to integrate:</p><h3>4.4. Enabling/Disabling Retries per Request</h3><p>Enable retries for specific requests by adding retryEnabledKey: trueto the extra map in Dio&#39;s request options:</p><pre>final response = await dio.get(&#39;/api/endpoint&#39;,<br>    options: Options(extra: {RetryInterceptor.retryEnabledKey: false}));</pre><p>If retryEnabledKey is not provided, retries are disabled by default.</p><h3>4.5. Specifying Retryable Status Codes per Request</h3><p>Retry requests based on specific HTTP status codes by adding retryErrorConditionsKey with a list of status codes to extra:</p><pre>final response = await dio.get(&#39;/api/endpoint&#39;,<br>    options: Options(extra: {<br>      RetryInterceptor.retryErrorConditionsKey: [408, 504], // Retry 408 and 504<br>    }));</pre><p>This example retries requests failing with 408 (Request Timeout) or 504 (Gateway Timeout) status codes, in addition to default DioExceptionType errors.</p><p>The default retry behavior is determined by the RetryConfig provided to the RetryInterceptor. Customize data class to adjust default retry settings as needed.</p><h3>4.6. <strong>Looking Ahead: Possible Improvements</strong></h3><p>While the RetryInterceptor provides a robust foundation, here are a few ways you could further enhance it:</p><ul><li><strong>Remote Configuration:</strong> For even greater flexibility, consider using Firebase Remote Config or similar services to manage your RetryConfig values (like maxRetries and baseDelayInMiliseconds) remotely. This would allow you to adjust your retry strategy on the fly without app updates, which is particularly useful for responding to changing network conditions or server loads.</li><li><strong>Idempotency Reminder:</strong> It’s crucial to remember that retry mechanisms are most effective for <strong>idempotent requests</strong> — requests that can be safely repeated without causing unintended side effects. Ensure that the API endpoints you are applying retries to are designed to be idempotent. For non-idempotent requests (like certain types of write operations), you might need to implement additional safeguards or avoid retries altogether.</li></ul><h3>5. Wrapping Up</h3><p>Implementing retry interceptors with Dio is a fantastic way to level up the robustness of your Flutter apps! Let’s recap the key points to remember:</p><ul><li><strong>Interceptors are powerful middleware</strong> in Dio, allowing you to centralize network logic and keep your code clean.</li><li><strong>Retry interceptors automatically handle transient errors</strong>, making your app more resilient to flaky networks.</li><li><strong>Intelligent retry strategies</strong>, like exponential backoff and selective retries, are crucial for efficient error recovery.</li><li><strong>Dio makes it easy to implement retry logic</strong> with interceptors and request options, giving you fine-grained control.</li></ul><p>By incorporating these techniques, you can significantly improve your app’s robustness and provide a better user experience.</p><p>Have you implemented retry logic in your Flutter apps before? What strategies worked best for you? I’d love to hear about your experiences in the comments! Feel free to share your thoughts or connect with me on <a href="https://www.linkedin.com/in/jdavifranco/">LinkedIn</a> for further discussions.</p><p>Thanks for reading 🚀 and happy coding on your Flutter journey!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26ab3c157483" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to migrate shared preferences from Android/iOS to Flutter]]></title>
            <link>https://medium.com/@jdavifranco/how-to-migrate-shared-preferences-from-android-ios-to-flutter-f1f06f39d8ab?source=rss-730922167b5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1f06f39d8ab</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[João Davi Franco]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 03:01:32 GMT</pubDate>
            <atom:updated>2024-12-19T18:52:59.334Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s learn how to migrate Android and iOS shared preferences to Flutter.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*vb_8-_zyJtxpzv8iT01sdg.png" /></figure><p>Shared preferences are great for storing user information that doesn’t belong in a database, like language preferences, theme settings, or onboarding status. If you’re migrating your native app to Flutter, you probably don’t want to make existing users go through onboarding again, right? Or lose the theme they’ve already chosen? In this article, I’ll show you how to migrate these settings to Flutter using the shared_preferences library and method channels. Let&#39;s get started!</p><h3>Flutter Shared Preferences</h3><p>In Flutter, the shared_preferences library helps us save settings or small configuration data locally by providing an interface for the native APIs. The library uses the SharedPreferences API for Android and UserDefaults for iOS, but we don&#39;t need to worry about those details when using this library. However, when migrating from Android or iOS, you need a way to bring over the existing preferences to avoid starting fresh.</p><p>To make this work, we’ll use <strong>method channels</strong>, which allow Flutter to call native APIs. If you’re unfamiliar with method channels, don’t worry — you can check out the Flutter documentation <a href="https://docs.flutter.dev/platform-integration/platform-channels">here</a> for a deeper dive.</p><p>It is important to note that the UserDefaults file used by the library is the same as the native one. According to the library documentation, it provides an option to change the prefix to an empty string. This way, we can access all the native keys from iOS without needing to do any migration. However, this approach has limitations because most projects won&#39;t have consistent key names between Android and iOS platforms, and on Android, it&#39;s possible to have multiple SharedPreferences files. To handle these use cases, the method channel approach is more flexible and robust.</p><h3>How to Migrate Shared Preferences from Android</h3><p>On Android, shared preferences are stored in SharedPreferences files. To migrate them:</p><ol><li>Use a method channel to communicate with the native Android code.</li><li>Retrieve the shared preferences data using Android’s SharedPreferences API.</li><li>Pass the data to Flutter’s shared_preferences library.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd2e6c27d46ec0df3cc0914a86a384e7/href">https://medium.com/media/bd2e6c27d46ec0df3cc0914a86a384e7/href</a></iframe><h3>How to Migrate Shared Preferences from iOS</h3><p>On iOS, shared preferences are stored in UserDefaults. The process is similar:</p><ol><li>Use a method channel to connect Flutter and the native iOS code.</li><li>Fetch the preferences using UserDefaults.</li><li>Send the data to Flutter.</li></ol><p>Here’s how it looks in Swift:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e3456c35236b648824202e52446c7d4/href">https://medium.com/media/4e3456c35236b648824202e52446c7d4/href</a></iframe><h3>Using the MigrateSharedPreferences class</h3><p>To make the migration easier, I created a MigrateSharedPreferencesclass. This class:</p><ul><li>Retrieves the preferences from Android and iOS.</li><li>Maps native keys to Flutter keys if necessary (useful when key names are different).</li><li>Handles conflicts by ensuring consistent naming.</li></ul><p>In the example, only the keys present in the map are migrated. This is probably the most common use case, as it’s likely that shared preferences keys between Android and iOS are not the same and don’t follow the same naming conventions. By mapping the keys, we ensure consistent naming and avoid duplicates or conflicts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5454bd7843f30e9d680a4cfa09222d23/href">https://medium.com/media/5454bd7843f30e9d680a4cfa09222d23/href</a></iframe><h3>Special Migration Cases</h3><p>Now that we know how to migrate the shared preferences from Android and iOS to flutter, let’s look at some specific scenarios you might encounter during migration.</p><h4>1. Android: Multiple Shared Preferences Files</h4><p>In Android, it’s possible to have multiple SharedPreferences files. This can be a good way to organize settings for different contexts in the app. To handle this case, you&#39;ll need to retrieve keys from each file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/838006cd699c0ddea1d5749a750722d6/href">https://medium.com/media/838006cd699c0ddea1d5749a750722d6/href</a></iframe><h4>2. Android: Data Store</h4><p>If your app has already migrated to the Data Store API — which is the new way of storing shared preferences data in Android — and you need to migrate this data too, here’s how to do it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6a1d2a5514d485ff3b813de226aba40/href">https://medium.com/media/b6a1d2a5514d485ff3b813de226aba40/href</a></iframe><p>To access DataStore from native code, you must add the DataStore dependency in the build.gradle file. In this example, the Data Store version used is androidx.datastore:datastore-preferences:1.0.0. To avoid issues, ensure the version of the DataStore API matches the one used in the Android project.</p><h3>Wrapping Up</h3><p>Migrating shared preferences ensures a seamless transition for users when moving to Flutter. Here’s what you should remember:</p><ul><li>Use <strong>method channels</strong> to access native shared preferences on Android and iOS.</li><li>Handle edge cases like multiple shared preferences files.</li><li>Standardize key names to avoid conflicts and maintain consistency.</li></ul><p>And that’s it! You now know how to migrate shared preferences from Android and iOS to Flutter. Whether it’s onboarding status, theme settings, or something else, this approach ensures users won’t lose their preferences.</p><p>If you’ve faced any challenges during migration, let me know in the comments — I’d love to hear your experience and help where I can! Or if you’d like to discuss more, connect with me on <a href="https://www.linkedin.com/in/jdavifranco/">LinkedIn</a>.</p><p>Thanks for reading, and I hope this guide helps you on your Flutter journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1f06f39d8ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestedScrollView Widget Explained — Flutter]]></title>
            <link>https://medium.com/@jdavifranco/nestedscrollview-widget-explained-flutter-4145e42faee0?source=rss-730922167b5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4145e42faee0</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[João Davi Franco]]></dc:creator>
            <pubDate>Tue, 05 Apr 2022 22:42:47 GMT</pubDate>
            <atom:updated>2022-04-18T19:29:40.918Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s learn what is the Flutter NestedScrollView widget, when to use it and how it works.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpbFOSESkrYve0ey2HPq0A.jpeg" /></figure><p>Scrolling is a good way to show content that does not fit on the screen or to show Lists that have a large number of items. In Flutter, we have nice widgets for those use cases, like <em>ListView</em>,<em> GridView</em>, and <em>SingleChildScrollView</em>. Still, sometimes we want to have more complex scrolling with multiple lists and grids, and an app bar that expands and collapses according to scroll actions on the screen, the limit here is your creativity. And for those complex use cases, we have the <em>NestedScrollView</em> widget.</p><h3>— What is the NestedScrolView?</h3><p>It is a scroll view that has multiple scrolling views nested inside of it. This widget creates custom scroll controllers for controlling and linking their position so they can look like one coherent scroll view, this way you don’t need to worry about keeping the nested scroll views synchronized, the <em>NestedScrollView</em> widget does that for you. But there is a downside, it is not possible to add explicit controllers for the scroll views in the body. That’s why it is important to know when it is a good idea to use this widget.</p><h3>— When to use the NestedScrollView in Flutter?</h3><p>To begin with, the most common use case is a <a href="https://api.flutter.dev/flutter/material/SliverAppBar-class.html"><em>SliverAppBar</em></a> with a <a href="https://api.flutter.dev/flutter/material/TabBar-class.html"><em>TabBar</em></a> and a <a href="https://api.flutter.dev/flutter/material/TabBarView-class.html"><em>TabBarView</em></a> in the body, where scrollable content varies depending on the tab selected. In this case, the <em>NestedScrollView</em> works to maintain the <em>SliverAppBar</em> collapsed or expanded according to actions in the nested scroll views, which saves a lot of work. Even though that is the most common use case, it can be used in a lot of different ways where you need to have nested scroll views, for example, you could have a grid and a list in the body and a <em>SliverAppBar</em> in the <em>headerSliverBuilder</em>, or any other configuration you may come up with.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c56370853605238841476760c63ecbe8/href">https://medium.com/media/c56370853605238841476760c63ecbe8/href</a></iframe><p>The required arguments to use the <em>NestedScrollView</em> are the <em>headerSliverBuilder </em>which accepts a list of <a href="https://docs.flutter.dev/development/ui/advanced/slivers"><em>slivers</em></a> and the <em>body</em> that accepts a single child, but it also has many other optional arguments, like [<a href="https://api.flutter.dev/flutter/widgets/ScrollPhysics-class.html"><em>physics</em></a><em>]</em> or [<a href="http://The axis along which the scroll view scrolls."><em>scrollDirection</em></a><em>]. </em>To sum up<em>, </em>here are some things to keep in mind when using this widget. The <em>NestedScrollView</em> widget is better for use cases where you want to have nested scrolling views that should look like a single scroll view, that’s because they will all have the same scroll controller and their position will be intrinsically linked, which means you can’t scroll the scroll views separately in the body. For this reason, consider using it if there is no need for controlling the position of the scroll views independently.</p><h3>— How does the NestedScrollView work?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F13HBDT4QSTpveU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fign-describe-plans-13HBDT4QSTpveU&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExaW9lZzF2bHdoNXpvM3o4czVjcXE3MW9uZzY4cGhlbnJiaTY2dWp0dSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F13HBDT4QSTpveU%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/855b07b0454c411d67da52df543ac22a/href">https://medium.com/media/855b07b0454c411d67da52df543ac22a/href</a></iframe><p>To make the nested scroll views look like one coherent scroll view, the <em>NestedScrollView</em> widget uses two custom<em> </em><a href="https://api.flutter.dev/flutter/widgets/ScrollController-class.html"><em>ScrollControllers</em></a>, the outer scroll controller for the scroll view inside the <em>headerSliverBuilder</em>, and the inner scroll controller, for the scrolling views inside the <em>body</em>. Yes, it uses only one scroll controller for all the possible scrolling views in the body. To make that happen, the body is wrapped in a<a href="https://api.flutter.dev/flutter/widgets/PrimaryScrollController-class.html"> PrimaryScrollController</a>, that associates a scroll controller to its subtree, so all scroll views inside the body should use this scroll controller, and that’s why you can’t add one explicitly without breaking the <em>NestedScrollView</em> functionality. Also, that’s why it is better to use this widget when the scroll views in the body should all behave like one.</p><h3>Useful tips for working with the NestedScrollView in Flutter</h3><p>Now that we know how it works and when to use it, here are some tips to help you make use of this awesome widget.</p><h4><strong>How to access the inner and outer scroll controllers?</strong></h4><p>If there is a need to control programmatically the position of the outer scroll view or the inner one, you can do it by using the<em> NestedScrollView</em> state object, which you can access through the <em>context</em> of a child widget.</p><p>Let’s see how to animate the outer and inner scroll views to a specific offset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f11876f10dde1a4282e6c363c3063c8/href">https://medium.com/media/0f11876f10dde1a4282e6c363c3063c8/href</a></iframe><p>That’s nice, right? But keep in mind that when calling the [animateTo] method in the inner controller position it will animate the whole body.</p><h4><strong>How to control a single scrolling view inside the body?</strong></h4><p>Well, this case is kind of tricky since there is only one scroll controller for the body. However, there is a workaround if you need access to a particular scrolling view position.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ecce4b85d69af106d29cad084785eb9/href">https://medium.com/media/3ecce4b85d69af106d29cad084785eb9/href</a></iframe><p>The <em>Scrollable.of(context)</em> method above returns the closest <em>ScrollableState</em> to the <em>context </em>passed, so it should be called in a place in the widget tree that is under the scroll view you need to control.</p><h3>Conclusion</h3><p>As we have seen, the <em>NestedScrollView</em> widget can be very helpful for complex use cases, but it is important to know when to use it. And now that you understand the widget, when to use it, and how it works, I hope it will be easier to work with nested scrolling views in the future. If there are any questions or suggestions let me know, I would gladly read and reply to them. If you enjoyed this article, follow me for more content about Flutter.</p><p>May this article help you in your Flutter journey, Thanks a lot!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4145e42faee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>