<?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 Sneha S on Medium]]></title>
        <description><![CDATA[Stories by Sneha S on Medium]]></description>
        <link>https://medium.com/@sneha.s_36687?source=rss-f50ffffc2644------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QJP4Z1haxIXegRKBSZl7og.jpeg</url>
            <title>Stories by Sneha S on Medium</title>
            <link>https://medium.com/@sneha.s_36687?source=rss-f50ffffc2644------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:43:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sneha.s_36687/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[Exploring Cupertino and Material Updates in Flutter 3.27.0]]></title>
            <link>https://medium.com/canopas/exploring-cupertino-and-material-updates-in-flutter-3-27-0-cb4c76e222e1?source=rss-f50ffffc2644------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb4c76e222e1</guid>
            <category><![CDATA[flutter-update]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[new-releases]]></category>
            <dc:creator><![CDATA[Sneha S]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 10:59:55 GMT</pubDate>
            <atom:updated>2024-12-30T05:26:56.372Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let’s dive into Cupertino and Material Updates in Flutter 3.27.0</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HKpD9Bz4YP4214lDD5ZXw.png" /></figure><p>Flutter 3.27.0 arrived with a bang, bringing a wave of improvements to both <strong>performance and developer experience.</strong> This release shows how Flutter is always getting better and helping developers make great apps.</p><p>In this article, we’ll explore the key updates of the Cupertino and Material widgets in Flutter 3.27.0.</p><p>Ready? Let’s dive in!</p><h4>SliverFloatingHeader</h4><p>Just like Google Photos, The SliverFloatingHeader is a widget designed to create headers that appear when the user scrolls forward and gracefully disappear when scrolling in the opposite direction.</p><pre>CustomScrollView(<br>  slivers: [<br>    SliverFloatingHeader(<br>        child: Container(<br>      padding: const EdgeInsets.all(10),<br>      decoration: BoxDecoration(<br>        borderRadius: BorderRadius.circular(10),<br>        color: Colors.orange,<br>      ),<br>      child: const Text(<br>        &quot;Sliver Floating Header like Google photos&quot;,<br>        style: TextStyle(<br>          fontSize: 20,<br>          fontWeight: FontWeight.bold,<br>          color: Colors.black,<br>        ),<br>      ),<br>    )),<br>    SliverList(<br>      delegate: SliverChildBuilderDelegate(<br>        (context, index) {<br>          return ListTile(<br>            title: Text(&quot;Item $index&quot;),<br>            tileColor: index.isEven? Colors.grey.shade300 : Colors.grey.shade100,<br>          );<br>        },<br>        childCount: 100,<br>      ),<br>    ),<br>  ],<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*gewh76wL9PkJNfsswHX-UA.gif" /><figcaption>SliverFloatingHeader</figcaption></figure><h3>Tubular Figures</h3><p>Have you ever faced UI misalignment when displaying monospaced text like DateTime, such as 01:00 PM or 02:30 PM? I encountered this issue while building the <strong>Canbook</strong> app, where I needed to display time slots. Initially, I tried calculating the width based on the thickest character (0) to fix the alignment.</p><p>How can we improve the UI for rendering monospaced text like DateTime and time, and maintain alignment and consistency for dynamic text updates?</p><p>In the old UI implementation, digits had variable widths due to the default font settings. This resulted in inconsistent alignment.</p><pre>SingleChildScrollView(<br>  child: Wrap(<br>    alignment: WrapAlignment.start,<br>    crossAxisAlignment: WrapCrossAlignment.center,<br>    spacing: 8,<br>    runSpacing: 8,<br>    children: List.generate(30, (index) {<br>      final time = DateTime.now().add(Duration(minutes: (index) * 15));<br>      return Container(<br>        padding: const EdgeInsets.all(8),<br>        decoration: BoxDecoration(<br>          border: Border.all(<br>            color: Colors.white,<br>          ),<br>          borderRadius: BorderRadius.circular(8),<br>        ),<br>        child: Text(<br>          DateFormat(&#39;hh:mm a&#39;).format(time),<br>          style: const TextStyle(<br>              fontFeatures: [FontFeature.tabularFigures()],<br>              color: Colors.white),<br>        ),<br>      );<br>    }),<br>  ),<br>);</pre><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aOcD3q2aR3SpoOgLtvyQg.png" /><figcaption>Inconsistent Alignment</figcaption></figure><p>FontFeature.tabularFigures() feature ensures that each character occupies the same width.</p><p>This feature enables the use of tabular figures for fonts with both proportional (varying width) and tabular figures. Tabular figures are monospaced, meaning all characters have the same width, making them ideal for aligning text in tables, lists, or dynamic UI elements like time slots or numeric data.</p><pre>Text(<br>  DateFormat(&#39;hh:mm a&#39;).format(time),<br>  style: const TextStyle(<br>      fontFeatures: [FontFeature.tabularFigures()],<br>      color: Colors.white),<br>),</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQIzcyGXVjKEkAcOSOVa8g.png" /><figcaption>FontFeatures with tabularFigures</figcaption></figure><h3>CupertinoSliverNavigationBar</h3><p>With the latest update, both CupertinoNavigationBar and CupertinoSliverNavigationBar now feature transparent backgrounds until content scrolls underneath them.</p><p>This enables,</p><ul><li>The navigation bar to match the background color in its expanded state.</li><li>A customizable color in its collapsed state.</li><li>Smooth transitions between these colors as the user scrolls.</li></ul><pre>CustomScrollView(<br>  slivers: [<br>    const CupertinoSliverNavigationBar(<br>     largeTitle : Text(<br>        &#39;Cupertino Transparent Navigation Bar&#39;,<br>        style: TextStyle(color: Colors.white, fontSize: 20),<br>      ),<br>      backgroundColor: Colors.transparent,<br>    ),<br>    SliverList(<br>      delegate: SliverChildBuilderDelegate(<br>        (context, index) {<br>          return ListTile(<br>            title: Text(&quot;Item $index&quot;),<br>          );<br>        },<br>        childCount: 100,<br>      ),<br>    ),<br>  ],<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*hXFck4oh8sOflLO44YVwdQ.gif" /><figcaption>CupertinoSliverNavigationBar</figcaption></figure><h3>Repeat Animation</h3><p>Flutter’s repeat method allows animations to run infinitely. But what if you want the animation to run for a specific number of times?</p><p>Now, with the addition of the count parameter, the repeat method can restart the animation and perform a set number of iterations before stopping.</p><p>If no value is provided for count, the animation will repeat indefinitely.</p><pre>@override<br>void initState() {<br>  super.initState();<br>  controller = AnimationController(<br>    duration: const Duration(seconds: 2),<br>    vsync: this,<br>  );<br>  animation = Tween&lt;double&gt;(begin: 100, end: 300).animate(controller)<br>    ..addListener(() {<br>      setState(() {});<br>    });<br>}<br><br>@override<br>Widget build(BuildContext context) {<br>  return Scaffold(<br>    body: Center(<br>      child: Container(<br>          width: animation.value,<br>          height: animation.value,<br>          color: Colors.yellow),<br>    ),<br>    floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,<br>    floatingActionButton: FloatingActionButton.extended(<br>      onPressed: () {<br>        controller.repeat(count: 2);<br>      },<br>      label: Text(&quot;Start Animation&quot;),<br>    ),<br>  );<br>}<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*2e_U6UexAs_w_Ek7psHw8A.gif" /></figure><h3>Row and Column Spacing</h3><p>With the release of Flutter 3.27.0, Row and Column widgets now support the spacing parameter, eliminating the need for manual SizedBox or Padding to add spacing between child widgets.</p><p>Now, with Flutter 3.27.0, you can simplify the layout by directly using the spacing property.</p><p>Using SizedBox for spacing between children,</p><pre>@override<br>Widget build(BuildContext context) {<br>  return Column(<br>    children: [<br>      _item(),<br>      const SizedBox(height: 16),<br>      _item(),<br>      const SizedBox(height: 16),<br>      _item(),<br>      const SizedBox(height: 16),<br>      _item(),<br>      const SizedBox(height: 16),<br>      _item(),<br>    ],<br>  );<br>}</pre><p>With Updates,</p><pre> @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      spacing: 16,<br>      children: [<br>        _item(),<br>        _item(),<br>        _item(),<br>        _item(),<br>      ],<br>    );<br>  }</pre><h3>Tap to scroll to the item in CupertinoPicker</h3><p>CupertinoPicker now supports tapping on an item to automatically scroll to it, to navigate directly to the selected item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*ib67FyxmWrs6UPp3cPoaVw.gif" /></figure><h3>Customize tab indicator animation</h3><p>Similar to Android’s tab indicator behavior, you can set the mode by which the selection indicator should animate when moving between destinations, <strong>Linear</strong> or <strong>Elastic</strong>.</p><p>TabBar.indicatorAnimation property, which allows you to customize the animation behavior of the tab indicator when switching between tabs.</p><ul><li>TabIndicatorAnimation.linear: A smooth, linear animation (default when indicatorAnimation is null and indicatorSize is TabBarIndicatorSize.tab ).</li><li>TabIndicatorAnimation.elastic: A bouncing, elastic animation (when indicatorSize is TabBarIndicatorSize.label)</li></ul><pre>DefaultTabController(<br>  length: 2,<br>  child: Scaffold(<br>    appBar: AppBar(<br>      title: const Text(&#39;Tab Indicator Animation&#39;),<br>      bottom: const TabBar(<br>        indicatorAnimation: TabIndicatorAnimation.elastic,<br>        tabs: &lt;Widget&gt;[<br>          Tab(text: &#39;Tab 1&#39;),<br>          Tab(text: &#39;Tab 2 with long text&#39;),<br>        ],<br>      ),<br>    ),<br>    body: TabBarView(),<br>  ),<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*XyI93BTYqxFddyKYaMzgHw.gif" /><figcaption>Elastic Tab Indicator</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*XyI93BTYqxFddyKYaMzgHw.gif" /><figcaption>Linear Tab Indicator</figcaption></figure><p>This blog post was originally published on <a href="https://canopas.com/blog"><strong>canopas.com</strong></a><strong>.</strong></p><blockquote><em>To read the full version, please visit </em><a href="https://canopas.com/exploring-cupertino-and-material-updates-in-flutter-3-27-cb4c76e222e1"><strong><em>this blog</em></strong></a><em>.</em></blockquote><h3>We’re Grateful to have you with us on this journey!</h3><p>If you<strong> </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb4c76e222e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/exploring-cupertino-and-material-updates-in-flutter-3-27-0-cb4c76e222e1">Exploring Cupertino and Material Updates in Flutter 3.27.0</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Flutter Android App Deployment with GitHub Actions and fastlane]]></title>
            <link>https://medium.com/canopas/automate-flutter-android-app-deployment-with-github-actions-and-fastlane-68805b762b0d?source=rss-f50ffffc2644------2</link>
            <guid isPermaLink="false">https://medium.com/p/68805b762b0d</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[fastlane]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Sneha S]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 11:43:30 GMT</pubDate>
            <atom:updated>2024-12-04T11:44:07.321Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to auto-deploy the Flutter Android app with Github actions and fastlane.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oR3QWbScwHR55LQE7JK1IQ.png" /></figure><h3>Background</h3><p>This article is the second part of our series on automating the deployment process for Flutter apps. In the previous article, we explored how to automate the deployment of a Flutter iOS app.</p><p><strong>Part 1:</strong></p><p><a href="https://canopas.com/automate-flutter-ios-app-deployment-with-github-actions-and-codemagic-cli-4d063ea6ef08">Automate Flutter iOS App Deployment with GitHub Actions and Codemagic CLI</a></p><p>Now, we’ll set up a Github action for an Android application using fastlane.</p><p>By the end of this article, you’ll have an efficient distribution pipeline for your Android application.</p><p><strong>Why fastlane?</strong></p><p><strong>fastlane</strong> is a straightforward and efficient tool for integrating CI/CD pipelines into Android app development. It not only simplifies deployment but also handles tasks like generating screenshots, managing code signing, and automating releasing processes.</p><h3>Prerequisite</h3><p>Before diving in, ensure you have a Flutter application and a GitHub repository ready for your project.</p><p>A basic workflow setup is also essential to proceed, including checking out the repository and setting up the Flutter environment. Since this setup is covered in our previous article, we won’t repeat it here.</p><p>For detailed instructions on setting up the workflow and Flutter environment, refer to our <a href="https://canopas.com/automate-flutter-ios-app-deployment-with-github-actions-and-codemagic-cli-4d063ea6ef08">Basic Workflow Setup Guide.</a></p><p>Ready? Let’s go! 🚀</p><h3>Let’s Get Started</h3><p>We’ll break down the auto-deployment process into three key parts.</p><ol><li><strong>Configure Android Code Signing</strong></li><li><strong>Set Up fastlane</strong></li><li><strong>Add Jobs for Publishing the App</strong></li></ol><p>Let’s dive into each of these steps. 👇</p><h4>1. <strong>Configure Android Code Signing</strong></h4><p>To publish your app on the Play Store, it must be signed with a digital certificate. Android uses two signing keys for this process: <strong>Upload key</strong> and <strong>App signing key</strong>.</p><p><strong>What are these keys, and why are they important?</strong></p><p><strong>Upload Key</strong></p><p>The <strong>Upload Key</strong> is used to sign your app when you upload it to the Play Console. After uploading, Google Play will re-sign your app with the<strong> App Signing Key</strong> before distributing it to users.</p><ul><li>The <strong>Upload Key</strong> is essential for authenticating your app during uploads.</li><li>It needs to be kept secure to prevent unauthorized access and to protect the integrity of your app’s updates.</li></ul><p>To generate the <strong>Upload Key</strong>, follow the official <a href="https://developer.android.com/studio/publish/app-signing#sign-apk">Android Developer Guide on App Signing.</a></p><blockquote>While creating the Upload Key, make sure to remember the password and key alias that you set for the key. You’ll need these later when configuring Fastlane and setting up the deployment process.</blockquote><p>After following these steps, you will have the XXX.jks file at the selected file path.</p><p><strong>App Signing Key</strong></p><p>The <strong>App Signing Key</strong> is the primary key used by Google Play to sign your app before delivering it to users. This key ensures that:</p><ul><li>Your app updates are trusted by users.</li><li>Only apps signed with the same key can be installed or updated.</li><li>This key remains consistent throughout the lifetime of your app, providing security for future updates.</li></ul><p>To generate the <strong>App Signing Key</strong>, follow the step-by-step instructions in the <a href="https://docs.fastlane.tools/getting-started/android/setup/">Collect your Google credentials</a> section in the fastlane setup documentation guide.</p><p>When creating the upload key, a JSON file is generated and downloaded. This file contains essential credentials that you will need to authenticate and manage your app on the Play Console. It will be required in the later steps.</p><h3>Set Up Fastlane</h3><p>Now, that we have the <strong>Upload Key</strong> and <strong>App Signing Key</strong> ready, it’s time to set up <strong>fastlane</strong>.</p><h4>Install fastlane</h4><p>To get started, you’ll need to install fastlane on your machine.</p><pre># Using RubyGems(macOS/Linux/Windows)<br>sudo gem install fastlane<br><br># Alternatively using Homebrew(macOS)<br>brew install fastlane</pre><h4>Set Up fastlane in Your Project</h4><p>fastlane is installed, let’s configure it within your Flutter project.</p><p><strong>Initialize fastlane</strong></p><p>Open your terminal and navigate to your project’s root directory and change the directory to android. Then, run the following command.</p><pre>fastlane init</pre><p>During the setup process, you’ll be prompted with a series of questions:</p><ul><li><strong>Package Name</strong>: Provide the package name of your application. You can find it in your android/app/build.gradle file, under defaultConfig &gt; applicationId.</li></ul><p>For example:</p><pre>applicationId &quot;io.example.yourapp</pre><ul><li><strong>Path to JSON Secret File</strong>: Press Enter when asked for the path to your JSON secret file. We’ll set up it later.</li><li><strong>Download existing metadata and set up metadata management: </strong>Choose the option based on how you plan to manage app metadata and screenshots during deployment.</li><li><strong>Google Play Upload</strong>: When asked if you plan on uploading information to Google Play via fastlane, answer ’n’ (No). We will configure this in a later step.</li></ul><p>Now, you can see a newly created ./fastlane directory in your project. Inside this directory, you’ll find two key files:</p><ul><li><strong>Appfile</strong>: This file contains global configuration information for your app, such as the app’s package name and JSON key file.</li><li><strong>Fastfile</strong>: This file defines the “lanes,” which are sets of actions that drive the behavior of fastlane for various tasks.</li></ul><p>Now, open the <strong>Appfile</strong> and add the following line to specify the path to your JSON key file, which will be used for authenticating with the Google Play API.</p><p>Also, ensure that the <strong>package_name</strong> is set to the correct value for your app and set the JSON file path in the Appfile as follows</p><pre>json_key_file(&quot;google_play_api_key.json&quot;) # Path to the json secret file<br>package_name(&quot;com.exapmle.appname&quot;)</pre><p>🤔 Don’t worry!! We will add the google_play_api_key.json file in the next steps. Stay tuned!</p><h3>Add Secrets to the Repository</h3><p>In this step, we’ll add all the necessary environment variables and secrets that fastlane and the app will use during deployment.</p><p>To add new secrets and variables to your repository, go to <strong>Settings &gt; Secrets and Variables.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhQ2IavIOwHuj9QwUcA1bw.png" /><figcaption>Secrets For GitHub Action</figcaption></figure><ul><li><strong>APKSIGN_KEYSTORE_PASS</strong>: The password for the keystore that is set when creating the development.jks file.</li><li><strong>APKSIGN_KEY_ALIAS</strong>: The alias created for the key inside the keystore.</li><li><strong>APKSIGN_KEY_PASS</strong>: The password associated with the alias created for the app’s signing key.</li><li><strong>APKSIGN_KEYSTORE_BASE64: </strong>We’ll need to convert the development.jks keystore file into Base64 format to store it as a secret. For that, open the terminal and navigate to the directory where the development.jks file is located.<br>base64 -i &lt;File name&gt;| pbcopy</li></ul><p>Now that the Keystore is copied to your clipboard, paste this Base64 content as the value.</p><ul><li><strong>APP_PLAY_SERVICE_JSON_BASE64</strong>: Convert JSON file downloaded while creating Upload key to Base64 format in a similar way as the keystore file and it as secret.</li></ul><h4>Set up environment variables</h4><p>We will set up the environment variables for the deployment job. These variables will reference the secrets you added to your GitHub repository.</p><pre>jobs:<br>  android_deployment:<br>    runs-on: ubuntu-latest<br>    env:<br>      APP_PLAY_SERVICE_JSON: ${{ secrets.APP_PLAY_SERVICE_JSON_BASE64 }}<br>      APKSIGN_KEYSTORE_BASE64: ${{ secrets.APKSIGN_KEYSTORE_BASE64 }}<br>      APKSIGN_KEYSTORE_PASS: ${{ secrets.APKSIGN_KEYSTORE_PASS }}<br>      APKSIGN_KEY_ALIAS: ${{ secrets.APKSIGN_KEY_ALIAS }}<br>      APKSIGN_KEY_PASS: ${{ secrets.APKSIGN_KEY_PASS }}</pre><p>This blog post was originally published on <a href="https://canopas.com/blog"><strong>canopas.com</strong></a><strong>.</strong></p><blockquote><em>To read the full version, please visit </em><a href="https://canopas.com/automate-flutter-android-app-deployment-with-git-hub-actions-and-fastlane"><strong><em>this blog</em></strong></a><em>.</em></blockquote><h3>We’re Grateful to have you with us on this journey!</h3><p>If you<strong> </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68805b762b0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/automate-flutter-android-app-deployment-with-github-actions-and-fastlane-68805b762b0d">Automate Flutter Android App Deployment with GitHub Actions and fastlane</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Flutter iOS App Deployment with GitHub Actions and Codemagic CLI]]></title>
            <link>https://medium.com/canopas/automate-flutter-ios-app-deployment-with-github-actions-and-codemagic-cli-4d063ea6ef08?source=rss-f50ffffc2644------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d063ea6ef08</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[app-store]]></category>
            <category><![CDATA[autodeployment]]></category>
            <dc:creator><![CDATA[Sneha S]]></dc:creator>
            <pubDate>Tue, 22 Oct 2024 07:37:18 GMT</pubDate>
            <atom:updated>2024-11-15T09:41:58.819Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to use Codemagic CLI tools with GitHub Actions to deploy the iOS Flutter app.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3tbtZ2n_CaJUwHA-kdgnA.png" /><figcaption>Created by Canopas</figcaption></figure><h3>Background</h3><p>In this tutorial, we’ll set up an automated deployment process for a Flutter iOS application using GitHub Actions. You’ll learn how to create a workflow that runs Codemagic CLI tools to build your app and upload it to TestFlight.</p><p>By the end, you’ll have an efficient app distribution pipeline that saves time and effort, allowing you to focus more on development and less on manual deployments.</p><h3>Why Codemagic?</h3><p>Codemagic CLI tools are a free, open-source set of command-line utilities that power Codemagic’s CI/CD service.</p><p>When I first tried setting up auto-deployment for my iOS app, I faced several frustrating and hard-to-resolve pipeline failures. That’s when I discovered Codemagic CLI — it required no configuration and simplified the entire build automation process.</p><p>Since then, I’ve been happily using it! 😅</p><h3>Sponsored</h3><p>We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out <a href="https://justly.life/"><strong>Justly</strong></a> and start building your habits today!</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>Prerequisites</h3><p>Before you begin, ensure you have the following:</p><ul><li>An App Store account enrolled in the Apple Developer Program.</li><li>A Flutter application ready for deployment.</li><li>A GitHub repository is set up for your project.</li></ul><p>For this tutorial, I’ll be using the Flutter counter app as an example.</p><h3>Let’s get started! 👇</h3><p>To make it easier, I have divided the article into 3 separate sections.</p><ul><li>Basic Workflow Setup</li><li>Setting things up in App Store Connect</li><li>Add Jobs For Distribution</li></ul><p>Now, let’s walk through each of these steps together!</p><p>Ready? Let’s go! 🚀</p><h3>Basic Workflow Setup</h3><p>In this section, we’ll add a basic GitHub workflow setup.</p><h4>Step 1: Creating a Workflow File</h4><ol><li>Navigate to your project’s root directory.</li><li>If you don’t already have one, create a new directory named .github/workflows.</li><li>Inside this directory, create a new YAML file (e.g., ios.yml).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*hhx0EDguUp45PlLU1_0gEQ.png" /><figcaption>Create File in .github/workflows</figcaption></figure><h4>Step 2: Set up workflow trigger</h4><p>In the newly created YAML file, start by defining the workflow trigger</p><pre>name: Push iOS build on TestFlight<br><br>on:<br>  push:<br>    branches:<br>      - main</pre><p><strong>name</strong>: This is the name of the workflow. It will be displayed under the <strong>Actions</strong> tab in your GitHub repository.</p><p><strong>on</strong>: This defines the event that triggers the workflow. In this case, the workflow will be triggered automatically whenever code is pushed to the main branch (e.g. when a sub-branch is merged into main).</p><ul><li>There are other events you can use as triggers depending on your workflow needs, such as pull requests, tags, or schedule-based triggers.</li></ul><h4>Step 3: Set up the jobs</h4><pre>jobs:<br>  ios_deployment:<br>    runs-on: macos-latest</pre><p>A workflow is made up of one or more jobs.</p><p>Each job runs in a specific environment, specified by the runs-on attribute. In this case, we&#39;re using a macOS environment (macos-13), which is essential for building iOS apps.</p><h4>Step 4: Add the jobs</h4><pre>   steps:<br>      - name: Checkout Repo<br>        uses: actions/checkout@v4</pre><p><strong>Checkout</strong>: This action checks out your repository into the $GITHUB_WORKSPACE, allowing your workflow to access the code and resources in your repository.</p><pre>- name: Set up Flutter SDK<br>  uses: flutter-actions/setup-flutter@v3<br>  with:<br>    channel: stable<br>    version: 3.24.0</pre><p><strong>Set up Flutter SDK</strong>: This step configures the Flutter environment in GitHub Actions. Make sure the specified version is compatible with the version in your pubspec.yaml file.</p><p>By default, this action will use the latest version, but you can specify a different version as needed.</p><pre>- name: Install dependencies &amp; Lint check<br>  run: |<br>    flutter clean<br>    flutter pub get<br>    flutter analyze --fatal-infos</pre><p><strong>Install dependencies and lint check</strong>: In this step, we run flutter pub get to install all necessary dependencies for the project.</p><p>We also perform a lint check using dart analyze --fatal-infos. This lint check is optional; you can skip it if you prefer not to perform static analysis on your code.</p><p>Once you push this workflow file to the main branch, you will see a build queued in the Actions tab of the GitHub repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXD6LgTspOFlh4pBN2gNrQ.png" /><figcaption>Workflow on Github Action Tab</figcaption></figure><h3>Setting things up in App Store Connect</h3><p>Before we proceed, we need to set up your app in App Store Connect. Skip this step if you’ve already done it.</p><p>Let’s walk through them. 👇</p><h4>1. <strong>Create a Distribution certificate</strong></h4><p>You can follow <a href="https://developer.apple.com/help/account/create-certificates/create-developer-id-certificates">this</a> guide if you don’t have it.</p><blockquote>Skip this if you’ve a Distribution certificate already.</blockquote><h4>2. <strong>Create an App Bundle identifier</strong></h4><ul><li>Go to Identifiers and create a new ID. This bundle ID is required to create an app in the App Store.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuoZgGC4obJDq7G50Ied7Q.png" /><figcaption>Create an App Bundle Identifier</figcaption></figure><ul><li>Select <strong>App IDs</strong> and continue.</li><li>Select <strong>App</strong> to Register.</li><li>Provide a <strong>Description</strong>, <strong>Bundle ID</strong>, and check capabilities you need in the app.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-LVVUF0MZ6BVrE1V4aqxg.png" /><figcaption>Add Description, Bundle ID</figcaption></figure><ul><li>Click <strong>continue</strong> and now you have a new identifier for the app.</li></ul><h4>3. <strong>Create a Provisioning Profile</strong></h4><p>A Provisioning Profile is linked to a Distribution Certificate and identifies a team or organization. This profile authorizes your app to run on devices without needing Xcode.</p><ul><li>Go to the Profiles section and click on the <strong>+</strong> sign to create a new Provisioning Profile.</li><li>Select <strong>App Store Connect</strong> under <strong>Distibution </strong>and<strong> </strong>click<strong> Continue.</strong></li><li>Choose the <strong>App ID</strong> you created earlier and click <strong>Continue</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWcOQoDe2ZKNdzmaVxPl5w.png" /><figcaption>Select an App ID</figcaption></figure><ul><li>Select the Distribution Certificate for the Provisioning Profile and click <strong>Continue</strong>.</li><li>Add the Provisioning Profile name and click Continue.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUFGh3C-xCKl1lkQsEzHvA.png" /><figcaption>Download Provisioning Profile</figcaption></figure><ul><li>Download the Provisioning Profile.</li></ul><h4><strong>4. Create a New App</strong></h4><ul><li>Go to Apps and create a New App</li><li>Fill in the required details in the form and click on Create.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWcHkXCkLcSHBFKicPYdKQ.png" /><figcaption>Craete a new App on App Store</figcaption></figure><ul><li>Congratulations! You have successfully created a new app.</li></ul><h4><strong>5. Generate an API key</strong></h4><p>As per the Codemagic <a href="https://blog.codemagic.io/deploy-your-app-to-app-store-with-codemagic-cli-tools-and-github-actions/">guide</a>, to enable Codemagic CLI tools to upload and fetch data from App Store Connect, you’ll need to generate an App Store Connect API key with App Manager access.</p><ul><li>Log in to App Store Connect and navigate to Users and Access &gt; Integrations.</li><li>Click on the <strong>+</strong> sign to generate a new API key.</li><li>Provide a name for the key and choose an<strong> App Manager</strong> access level.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*xDjUiB7VnkemOwglH3xWKw.png" /></figure><ul><li>After generating the key, it will be listed among the active keys. Click <strong>Download API Key</strong> to save the private key for later use.</li></ul><blockquote><strong>Note:</strong> The key can only be downloaded once, so be sure to keep it at a secure location.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bUC4uuaKQ2nWnOmq.png" /></figure><ul><li>Save this <strong>Issuer ID</strong>, <strong>KEY ID</strong>, and the <strong>API Key</strong>, as we’ll need it later.</li></ul><h4><strong>6. Download the Certificate</strong></h4><ul><li>Download<strong> </strong>the distribution certificate you created in Step 5.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNCRCfmWVaQSlIcGjwgPOA.png" /><figcaption>Download Distribution Certificate</figcaption></figure><ul><li>Locate the downloaded certificate and open it using Keychain Access. Next, <strong>Export the certificate</strong> to create a file with a .p12 extension. You can save this file in your Downloads folder or any directory you prefer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUmE7XWkIvoppfYWeV3oBw.png" /><figcaption>Download the Certificate From KeyChain</figcaption></figure><ul><li>When you click to download, you’ll be prompted to set a password for the certificate. This password will be required to access the certificate, so make sure to remember it. You will need to add it as a variable in your workflow.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*S8D-SPZPHsvuVKrW79BooA.png" /><figcaption>Set password for Distibution certificate</figcaption></figure><p>Now we’ve completed all the basic setups for App Store Connect, it’s time to configure the environment variables for GitHub Actions.</p><p>This blog post was originally published on <a href="https://canopas.com/blog"><strong>canopas.com</strong></a><strong>.</strong></p><blockquote><em>To read the full version, please visit </em><a href="https://canopas.com/automate-flutter-ios-app-deployment-with-github-actions-and-codemagic-cli-4d063ea6ef08"><strong><em>this blog</em></strong><em>.</em></a></blockquote><h3>We’re Grateful to have you with us on this journey!</h3><p>If you<strong> </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d063ea6ef08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/automate-flutter-ios-app-deployment-with-github-actions-and-codemagic-cli-4d063ea6ef08">Automate Flutter iOS App Deployment with GitHub Actions and Codemagic CLI</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Achieve Effortless List Item Animation and Reordering in Flutter]]></title>
            <link>https://medium.com/canopas/how-to-achieve-effortless-list-item-animation-and-reordering-in-flutter-7947a4cebfa4?source=rss-f50ffffc2644------2</link>
            <guid isPermaLink="false">https://medium.com/p/7947a4cebfa4</guid>
            <category><![CDATA[reorderable-listview]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[animatedlis]]></category>
            <category><![CDATA[gridview]]></category>
            <dc:creator><![CDATA[Sneha S]]></dc:creator>
            <pubDate>Wed, 10 Jul 2024 10:06:38 GMT</pubDate>
            <atom:updated>2024-07-15T07:55:28.680Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore AnimatedReorderableListView for List Item Animation with Drag to Reorder in Listview and GridView in Flutter.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mV99WzywG9zN4pe_ZC_8ZA.png" /></figure><blockquote><em>Exciting News! Our blog has a new </em><a href="https://canopas.com/blog"><em>Home</em></a><em>! 🚀</em></blockquote><h4>Background</h4><p>In a world full of Flutter app creation, making things easy and fun for users is super important.</p><p>Recently, I needed to create a list where you could drag items around, and I wanted it to look cool with smooth animations. The built-in ReorderableList Flutter is good, but it lacked the fancy animations I hoped for.</p><p>Well, the animated_reorderable_list library is designed to elevate user experience by providing drag-and-drop functionality with neat animations to make your app more lively.</p><p>In this article, we’ll explore animated_reorderable_list and will see how easy it is to add animations with the drag-and-drop function for both Listview and GridView.</p><p><strong>What we’ll implement in this blog?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*9a-72k1NzK1uls4aTzLPow.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*whnis6VN0IsKDXsHMsOG0Q.gif" /></figure><h3>Sponsored</h3><p>We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out Justly and start building your habits today!</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><p><strong>You can find the full source code </strong><a href="https://github.com/canopas/animated_reorderable_list"><strong>here</strong></a><strong> and the library on </strong><a href="https://pub.dev/packages/animated_reorderable_list"><strong>pub.dev</strong></a><strong>.</strong></p><p><a href="https://pub.dev/packages/animated_reorderable_list">animated_reorderable_list | Flutter package</a></p><h3>Key Features</h3><p>Let’s take a closer look at the features of the library.</p><h4>Smooth Transition</h4><p>In Flutter AnimatedList, While inserting or removing items, the below items jump instead of making a smooth transition. So, this library provides a smooth transition while adding or removing items.</p><h4>Drag and Drop</h4><p>This library provides drag-and-drop support for both Listview and GridView and allows users to reorder items with animations.</p><h4>Built-in Animation Support</h4><p>There is built-in support for some animations like ScaleIn, FadeIn, and SizeIn.</p><h4>Simple Implementation</h4><p>In Flutter AnimatedList, updating the UI requires calling inserItem and removeItem methods through listState using a key. With this library, You can update the UI by just updating a list like ListView.</p><h4>Enhanced Performance</h4><p>This library is great for larger lists. it optimizes performance by rendering items only when they enter the viewport.</p><h3>How to Implement?</h3><p>Now, let’s get practical and see how you can use animated_reorderable_list in your own Flutter project.</p><h4>Add Dependency</h4><p>Add the following dependency in pubspec.yaml file.</p><pre>animated_reorderable_list: &lt;latest version&gt;</pre><h4>Getting Started</h4><p>This is a simple Todo app where we are going to implement animations while adding or removing items from the list. For simplicity, we will not implement UI from scratch.</p><p>You can find the full source code <a href="https://github.com/cp-sneha-s/animated_reorderable_demo">here</a>.</p><pre>class ActivityPage extends StatefulWidget {<br>  const ActivityPage({super.key});<br><br>  @override<br>  State&lt;ActivityPage&gt; createState() =&gt; _ActivityPageState();<br>}<br><br>class _ActivityPageState extends State&lt;ActivityPage&gt; {<br>....<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SafeArea(<br>      child: Scaffold(<br>        backgroundColor: Colors.black,<br>        appBar: AppBar(<br>       ....<br>        ),<br>        body: ListView.builder(<br>          padding: const EdgeInsets.all(16),<br>          itemCount: activities.length,<br>          itemBuilder: (BuildContext context, int index) {<br>            final activity = activities[index];<br>            return ActivityCard(<br>              key: ValueKey(activity),<br>              activity: activity.activity,<br>              why: activity.why,<br>              color: activity.color,<br>              selected: activity.selected,<br>              onChanged: (value) =&gt; _handleOnChanged(value, activity),<br>            );<br>          },<br>        ),<br>        floatingActionButton: FloatingActionButton(<br>          backgroundColor: Colors.orangeAccent,<br>          onPressed: _displayDialog,<br>          child: const Icon(Icons.add, color: Colors.black,),<br>        ),<br>      ),<br>    );<br>  }<br></pre><p>Run the app and see how it looks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*TDpWe2c4QeLo1hQ7aIU-lw.gif" /></figure><h4>Implement Animations</h4><p>Now, we are going to use the AnimatedListView, to implement animations while adding or removing the item from the list.</p><pre><br><br>class _ActivityPageState extends State&lt;ActivityPage&gt; {<br>....<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SafeArea(<br>     ....<br>//Replac Listview.builder with AnimatedList <br>        body: AnimatedListView(<br>          padding: const EdgeInsets.all(16),<br>//Pass List of items to be displayed<br>          items: activities,<br>          itemBuilder: (BuildContext context, int index) {<br>            final activity = activities[index];<br>            return ActivityCard(<br>              key: Key(activity.activity), //Add unique Key for each item<br>              activity: activity.activity,<br>              why: activity.why,<br>              color: Colors.primaries[index % Colors.primaries.length].shade50,<br>              selected: activity.selected,<br>              onChanged: (value) =&gt; _handleOnChanged(value, activity),<br>            );<br>          },<br>        ),<br>       ....<br>      ),<br>    );<br>  }<br><br>...<br>}</pre><p>Here, we just Replaced ListView.builder with AnimatedListView. It takes a list of items and itemBuilder function to build each item in the list. We have to pass a key to uniquely identify each item.</p><p>Let’s see what it looks like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*3fL5hm-WyWpqr0uLJDLyVg.gif" /></figure><p>You can see smooth transitions and fade in animation. It’s because default animations are set to FadeIn.<br>Let’s customize it.</p><h4>Customizing Animations</h4><pre>AnimatedListView(<br>  padding: const EdgeInsets.all(16),<br>  items: activities,<br>  itemBuilder: (BuildContext context, int index) {<br>....<br>  },<br> enterTransition: [<br>   FadeIn(<br>    duration: const Duration(<br>      seconds: 2,<br>     ),<br>    ),<br>    ScaleIn(duration: const Duration(seconds: 2), curve: Curves.bounceIn),<br>   ],<br> exitTransition: [SlideInLeft()],<br>),</pre><p>enterTransition: Specifies the enter tradition for items when they are added to the list.</p><p>exitTransition: Specifies the exit tradition for items when they are removed from the list.</p><p>Here we can add a List of animations that run concurrently, However, for customizations such as introducing delays, extending animation duration, or sequencing animations after one another, we can customize animation also.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*dgakjVicSkLW2g3tYH7gHg.gif" /></figure><p>one thing, we keep in mind is that if we add insertDuration or removeDuration then it will override the duration of a specific animation.</p><p>This blog post was originally published on <a href="https://canopas.com/blog"><strong>canopas.com</strong></a><strong>.</strong></p><blockquote><em>To read the full version, please visit </em><a href="https://canopas.com/how-to-achieve-effortless-list-item-animation-and-reordering-in-flutter-7947a4cebfa4"><strong><em>this blog</em></strong></a><em>.</em></blockquote><h3>We’re Grateful to have you with us on this journey!</h3><p>If you<strong> </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7947a4cebfa4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/how-to-achieve-effortless-list-item-animation-and-reordering-in-flutter-7947a4cebfa4">How to Achieve Effortless List Item Animation and Reordering in Flutter</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Adaptive Pageview in Flutter]]></title>
            <link>https://medium.com/canopas/how-to-implement-adaptive-pageview-in-flutter-45f2a75ada75?source=rss-f50ffffc2644------2</link>
            <guid isPermaLink="false">https://medium.com/p/45f2a75ada75</guid>
            <category><![CDATA[responsive-design]]></category>
            <category><![CDATA[pageviewcontroller]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Sneha S]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 10:08:59 GMT</pubDate>
            <atom:updated>2024-04-18T10:45:07.214Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to implement PageView to dynamically adjust its size based on the content it contains in Flutter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ac8b8nALvUJmznv37W950A.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><blockquote>Exciting News! Our blog has a new <a href="https://canopas.com/blog">Home</a>! 🚀</blockquote><h3>Background</h3><p>The <strong><em>PageView widget </em></strong>allows user to transition between different screens in their Flutter application. As per Flutter doc,</p><blockquote>PageView is a scrollable list that works page by page. Each child of a page view is forced to be the same size as the viewport.</blockquote><p>Each child within a PageView is typically constrained to the same size as the viewport, limiting flexibility in layout design. But what if we want our PageView to dynamically adjust its size based on the content it contains?</p><p>In this article, we’ll implement the PageView with children of different heights to make it flexible.</p><p>What we’ll achieve at the end of this blog?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*L_KoKKJf1C3p5TBFckz94w.gif" /></figure><p>You can find the full source code on <a href="https://github.com/cp-sneha-s/adaptive_page_view"><strong>GitHub</strong></a>.</p><h3>Sponsored</h3><p>We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out Justly and start building your habits today!</p><p><a href="https://justly.life/download">Justly: Habits, Goals, Journal</a></p><h3>Let’s get started</h3><p>First, let’s quickly have a look at the Pageview in Flutter, For simplicity, we have added a simple UI.</p><pre>class StarterPageView extends StatelessWidget {<br>  StarterPageView({super.key});<br><br><br>  final List&lt;int&gt; items= List.generate(5, (index) =&gt; index);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SizedBox(<br>      height: 400,<br>      child: PageView.builder(<br>        itemCount: items.length,<br>        itemBuilder: (context, index) {<br>          return Container(<br>              margin: const EdgeInsets.all(10),<br>              decoration: BoxDecoration(<br>                borderRadius: BorderRadius.circular(10),<br>                color:Colors.black,<br>              ),<br>              child: Wrap(<br>                children: List.generate(index+1, (index) {<br>                  return Container(<br>                    margin: const EdgeInsets.all(10),<br>                    decoration: BoxDecoration(<br>                      borderRadius: BorderRadius.circular(10),<br>                      color: Colors.yellow,<br>                    ),<br>                    height: 50,<br>                    child: ListTile(<br>                      title: Text(&#39;Page ${index+1}&#39;),<br>                    ),<br>                  );<br><br>                }),<br>              )<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>Here is the result,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*BLW1F8ePVgQuWTTEtafr9Q.gif" /></figure><p>The problem with the Pageview in Flutter is it can’t have dynamic height.</p><p>If we have a tab that might have a height of 100 px and another 200 px then it can’t adjust the height to the currently displayed page. 😞😞</p><p>Our goal? To create a PageView that adjusts its dimensions based on its content. So, Let’s start implementing it without wasting time.</p><h3>Implement Adaptive PageView</h3><p>We’ll divide implementation into 5 simple steps to make each step easy to understand.</p><h4>Implement SizeNotifier Widget</h4><p>To implement dynamic sizing within our PageView, we’ll start by implementing a widget that measures the size of the child and notifies the parent widget if the child&#39;s size is different than the previous one.</p><pre>class SizeNotifierWidget extends StatefulWidget {<br>  final Widget child;<br>  final ValueChanged&lt;Size&gt; onSizeChange;<br><br>  const SizeNotifierWidget({<br>    super.key,<br>    required this.child,<br>    required this.onSizeChange,<br>  });<br><br>  @override<br>  State&lt;SizeNotifierWidget&gt; createState() =&gt; _SizeNotifierWidgetState();<br>}<br><br>class _SizeNotifierWidgetState extends State&lt;SizeNotifierWidget&gt; {<br>  Size? _oldSize;<br><br>  @override<br>  void didUpdateWidget(covariant SizeNotifierWidget oldWidget) {<br>    WidgetsBinding.instance.addPostFrameCallback((_) =&gt; _notifySize());<br>    super.didUpdateWidget(oldWidget);<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return widget.child;<br>  }<br><br>  void _notifySize() {<br>    final size = context.size;<br>    if (size != null &amp;&amp; _oldSize != size) {<br>      _oldSize = size;<br>      widget.onSizeChange(size);<br>    }<br>  }<br>}</pre><p>This widget is used to monitor the size of its child widget and trigger a callback whenever that size changes. Let’s break it down,</p><p>It takes two required parameters,</p><ul><li>child: The child widget that this SizeNotifierWidget will render.</li><li>onSizeChange: A callback function that will be invoked whenever the size of this widget changes.</li></ul><p>Inside the didUpdateWidget() Method,</p><ul><li>This method is called whenever the widget is rebuilt with a different configuration.</li><li>Inside this method, a post-frame callback is added using WidgetsBinding.instance.addPostFrameCallback(). This callback ensures that _notifySize() is called after the frame is rendered. This is necessary because the size of a widget is only available after it has been laid out on the screen.</li></ul><h4>Implement PageView using SizeNotifier</h4><p>Now, we’ll use this widget to measure the size of the current item in the PageView. So, whenever the child has a different height then it notifies about that.</p><pre>class ThreePageScrollView extends StatefulWidget {<br>  final Widget current;<br><br>  const ThreePageScrollView({<br>    super.key,<br>    required this.current,<br>  });<br><br>  @override<br>  State&lt;ThreePageScrollView&gt; createState() =&gt; _ThreePageScrollViewState();<br>}<br><br>class _ThreePageScrollViewState extends State&lt;ThreePageScrollView&gt; {<br>  double? _currentItemHeight;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Stack(<br>      children: [<br>        Opacity(<br>          opacity: 0,<br>          child: SizeNotifierWidget(<br>            child: widget.current,<br>            onSizeChange: (size) {<br>              setState(() {<br>                _currentItemHeight = size.height;<br>              });<br>            },<br>          ),<br>        ),<br>        SizedBox(<br>            height: _currentItemHeight ?? 0,<br>            child: PageView(<br>              children: [<br>                widget.current,<br>              ],<br>            )),<br>      ],<br>    );<br>  }<br>}</pre><p>The code is pretty simple, here we’ve used the SizeNotifier widget to measure the size of the current item and set that size to give it to PageView.<br>Let’s add a simple UI to see if it’s working or not.</p><h4>Use Custom ThreePageScrollView</h4><p>We’ll add a simple UI to verify its functionality.</p><pre>class FinalPageView extends StatelessWidget {<br>  FinalPageView({super.key});<br><br>  int itemCount = 1; // Number of items in the page view<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return ThreePageScrollView(<br>      current: getItem(),<br>    );<br>  }<br><br>  Widget getItem() {<br>    return Container(<br>        margin: const EdgeInsets.all(10),<br>        decoration: BoxDecoration(<br>          borderRadius: BorderRadius.circular(10),<br>          color: Colors.black,<br>        ),<br>        child: Wrap(<br>          children: List.generate(itemCount, (index) {<br>            return Container(<br>              margin: const EdgeInsets.all(10),<br>              decoration: BoxDecoration(<br>                borderRadius: BorderRadius.circular(10),<br>                color: Colors.yellow,<br>              ),<br>              height: 50,<br>              child: ListTile(<br>                title: Text(&#39;Page ${index + 1}&#39;),<br>              ),<br>            );<br>          }),<br>        ));<br>  }<br>}</pre><p>The code is pretty straightforward, we have used our Custom ThreePageScrollView and added a child from the getItem() function. Let’s see what it looks like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*tKjX-KsTNKyFhD5Y_i_n0Q.png" /></figure><p>Ah, got it!!</p><p>Now let’s make it swipeable.😃</p><h4>Add PageController to PageView</h4><p>We’ll implement the PageViewController to manage PageView and to make it scrollable.</p><pre>class ThreePageScrollView extends StatefulWidget {<br>  final Widget current;<br>  final Widget? next;<br>  final Widget? previous;<br>  final Function(int)? onPageChanged;<br><br>  const ThreePageScrollView({<br>    super.key,<br>    required this.current,<br>    this.next,<br>    this.previous,<br>    required this.onPageChanged,<br>  });<br><br>  @override<br>  State&lt;ThreePageScrollView&gt; createState() =&gt; _ThreePageScrollViewState();<br>}<br><br>class _ThreePageScrollViewState extends State&lt;ThreePageScrollView&gt; {<br>  late PageController _pageController;<br><br>  double? _currentItemHeight;<br>  late int currentPage;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    currentPage = widget.previous == null ? 0 : 1;<br><br>    _pageController = PageController(initialPage: currentPage);<br>    _pageController.addListener(() {<br>      final newPage = _pageController.page?.toInt();<br>      if (newPage == null || newPage.toDouble() != _pageController.page) return;<br><br>      if (newPage == currentPage) {<br>        return;<br>      }<br><br>      _pageController.jumpToPage(1);<br>      widget.onPageChanged!(newPage &gt; currentPage ? 1 : -1);<br>      currentPage = 1;<br>    });<br>  }<br><br>  @override<br>  void didUpdateWidget(covariant ThreePageScrollView oldWidget) {<br>    super.didUpdateWidget(oldWidget);<br>    if (widget.previous != oldWidget.previous) {<br>      final newPage = widget.previous == null ? 0 : 1;<br>      if (newPage != currentPage) {<br>        currentPage = newPage;<br>        _pageController.jumpToPage(newPage);<br>      }<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Stack(<br>      children: [<br>      ....<br>        SizedBox(<br>            height: _currentItemHeight ?? 0,<br>            child: PageView(<br>              controller: _pageController,<br>              physics: const FastPageViewScrollPhysics(),<br>              children: [<br>                if (widget.previous != null) widget.previous!,<br>                widget.current,<br>                if (widget.next != null) widget.next!,<br>              ],<br>            )),<br>      ],<br>    );<br>  }<br>}</pre><p>Here we have —</p><p>Before implementing PageContoller, it’s essential to have the previous and next child other than the current one to make it scrollable. So, We have set the following parameters,</p><ul><li>next: A widget representing the next page.</li><li>previous: A widget representing the previous page.</li><li>onPageChanged(int): A callback function that is invoked when the page changes. It receives an integer parameter indicating the direction of the change (-1 for the previous, 1 for the next).</li></ul><p><strong>Variables</strong>: _pageController to manage PageView and currentPage variable is used to keep track of the current page index.</p><p><strong>initState() Method</strong></p><ul><li>Sets the initial page based on whether previous is provided. If previous is null, set the current page to 0; otherwise, set it to 1.</li><li>Adds a listener to _pageController to detect page changes. When the page changes, it calls widget.onPageChanged with the direction of the change.</li></ul><p><strong>didUpdateWidget() Method</strong></p><ul><li>It checks if previous has changed and updates the current page accordingly. If previous becomes null, it sets the current page to 0; otherwise, it sets it to 1.</li></ul><p>This blog post was originally published on <a href="https://canopas.com/blog"><strong>canopas.com</strong></a><strong>.</strong></p><blockquote><em>To read the full version, please visit </em><a href="https://canopas.com/how-to-implement-adaptive-pageview-in-flutter-45f2a75ada75"><strong><em>this blog</em></strong></a><em>.</em></blockquote><h3>We’re Grateful to have you with us on this journey!</h3><p>If you<strong> </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45f2a75ada75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/how-to-implement-adaptive-pageview-in-flutter-45f2a75ada75">How to Implement Adaptive Pageview in Flutter</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement 2D Scrollable TableView in Flutter]]></title>
            <link>https://medium.com/canopas/how-to-implement-2d-scrollable-tableview-in-flutter-a8b0fe703614?source=rss-f50ffffc2644------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8b0fe703614</guid>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[tableviews]]></category>
            <category><![CDATA[two-dimensional-arrays]]></category>
            <dc:creator><![CDATA[Sneha S]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 09:30:20 GMT</pubDate>
            <atom:updated>2024-04-28T14:15:27.399Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore Two Dimensional Scrollables in Flutter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Citsliklxv2hW1KBBKpPMg.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3>Background</h3><p>Tables are useful tools for efficient data organization within the application. Flutter’s latest update introduced a TwoDimensionalScrollView widget.</p><p>TwoDimensionalScrollView is a widget that combines the TwoDimensionalScrollable and TwoDimensionalViewport to create an interactive scrolling pane of content in both vertical and horizontal dimensions but using it directly is a bit challenging.</p><p><a href="https://dartpad.dev/?id=4424936c57ed13093eb389123383e894"><strong>Here</strong></a> is a demo code to implement 2D ScrollView in Flutter.</p><h3>Table of Contents</h3><pre>· <a href="#df83">Introduction</a><br>· <a href="#0b29">Implementation</a><br>   - <a href="#b92a">Add the dependency</a><br>   - <a href="#c853">Adding TableView to a screen</a><br>· <a href="#807c">TableSpan</a><br>   - <a href="#f30d">Add a border</a><br>   - <a href="#d020">Add color</a><br>   - <a href="#6e07">TableSpan.extent</a><br>   - <a href="#f6b8">void Function(PointerEnterEvent)? onEnter</a><br>   - <a href="#71d3">void Function(PointerExitEvent)? onExit</a><br>   - <a href="#973e">recognizerFactories</a><br>   - <a href="#8984">Add a Padding</a><br>· <a href="#58aa">Pinning the rows and columns</a><br>· <a href="#08c4">ScrollableDetail</a><br>· <a href="#aa44">cacheExtent</a><br>· <a href="#cf1e">DiagonalDragBehavior</a><br>· <a href="#a81b">Conclusion</a></pre><h3>Sponsored</h3><p>Positive thinking leads to positive outcomes. Try out <a href="https://justly.life/dl"><strong>Justly</strong></a><strong>, </strong>build good habits, and start thinking positively today.</p><p><a href="https://justly.life/dl?source=post_page-----db17e3aa90b0--------------------------------">Justly: Habits, Goals, Journal</a></p><h3>Introduction</h3><p>Flutter’s prebuilt widget has great performance and it renders children lazily only when it is in the view and improves the performance but Flutter has released a new package two_dimensional_scrollables to implement a TableView that scrolls in both the vertical and horizontal axes.</p><p>In this tutorial, we’ll explore this package to implement a very simple Tableview and we’ll see how we can customize it.</p><p>You can find the full source code <a href="https://gist.github.com/cp-sneha-s/d2375b2a624f5650fa3836a84805b15f"><strong>here</strong></a>.</p><h3>Implementation</h3><h4>Add the Dependency</h4><p>To add the dependency, first open <strong>pubspec.yaml</strong> file and then add the dependency.</p><pre>dependencies:<br>  two_dimensional_scrollables: &lt;latest version&gt;</pre><h4>Adding TableView to a screen</h4><p>When you are adding a TableView, there are two constructors you can use:</p><p><strong>TableView.list</strong>: This one is similar to Flutter’s ListView. It adds all the cells at once and works well for shorter lists.</p><p><strong>Tableview.builder</strong>: It adds children lazily when the view has come into the viewport. Great for larger lists where you don’t want to load everything at once!</p><p>Let’s create a simple Tableview to display the following information.</p><pre>class Employee {<br> final String id;<br> final String name;<br> final String role;<br> final String email;<br>     Employee({<br>         required this.id,<br>         required this.name,<br>         required this.role,<br>         required this.email});<br> static get getEmployees{<br>    return [<br>      Employee(id: &#39;1&#39;, name: &#39;John Doe&#39;, role: &#39;Manager&#39;, email: &#39;john@example.com&#39;),<br>      Employee(id: &#39;2&#39;, name: &#39;Jane Smith&#39;, role: &#39;Developer&#39;, email: &#39;jane@example.com&#39;),<br>      Employee(id: &#39;3&#39;, name: &#39;Mike Johnson&#39;, role: &#39;Designer&#39;, email: &#39;mike@example.com&#39;),<br>      Employee(id: &#39;4&#39;, name: &#39;Emily Brown&#39;, role: &#39;HR Specialist&#39;,email: &#39;emily@example.com&#39;),<br>      Employee(id: &#39;5&#39;, name: &#39;Alex Lee&#39;, role: &#39;Marketing Analyst&#39;, email: &#39;alex@example.com&#39;),<br>      Employee(id: &#39;6&#39;, name: &#39;John Doe&#39;, role: &#39;Manager&#39;, email: &#39;john@example.com&#39;),<br>      Employee(id: &#39;7&#39;, name: &#39;Jane Smith&#39;, role: &#39;Developer&#39;, email: &#39;jane@example.com&#39;),<br>      Employee(id: &#39;8&#39;, name: &#39;Mike Johnson&#39;, role: &#39;Designer&#39;, email: &#39;mike@example.com&#39;),<br>      Employee(id: &#39;9&#39;, name: &#39;Emily Brown&#39;, role: &#39;HR Specialist&#39;,email: &#39;emily@example.com&#39;),<br>      Employee(id: &#39;10&#39;, name: &#39;Alex Lee&#39;, role: &#39;Marketing Analyst&#39;, email: &#39;alex@example.com&#39;),<br>     ];<br>  }<br>}</pre><p>Here is a basic example code of TableView.builder.</p><pre><br>class TwoDimensionalScrollableDemo extends StatelessWidget {<br>   TwoDimensionalScrollableDemo({super.key});<br><br>final  List&lt;Employee&gt; employees = Employee.getEmployees;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&quot;Table view Demo&quot;),<br>      ),<br>      body: TableView.builder(<br>          columnCount: 2,<br>          rowCount: 11,<br>          columnBuilder: buildTableSpan,<br>          rowBuilder: buildTableSpan,<br>          cellBuilder: (BuildContext context, TableVicinity vicinity) {<br>            return Container(child: Center(child: addText(vicinity)));<br>          }),<br>    );<br>  }<br><br>  TableSpan buildTableSpan(int index){<br>    return TableSpan(extent: FixedTableSpanExtent(50));<br>  }<br><br>  Widget addText(TableVicinity vicinity) {<br>    if (vicinity.yIndex == 0 &amp;&amp; vicinity.xIndex == 0) {<br>      return const Text(&quot;Index&quot;);<br>    } else if (vicinity.yIndex == 0 &amp;&amp; vicinity.xIndex == 1) {<br>      return const Text(&quot;name&quot;);<br>    } else if (vicinity.xIndex == 0) {<br>      return Text(employees[vicinity.yIndex-1].id);<br>    } else if (vicinity.xIndex == 1) {<br>      return Text(employees[vicinity.yIndex-1].name);<br>    }<br>    return Text(&quot;&quot;);<br>  }<br>}</pre><p>This is pretty good for just a few lines of code. Let’s break down the required parameters of the TableView.builder.</p><p><strong>columnCount</strong>: This parameter sets the number of columns in the table.</p><p><strong>rowCount</strong>: This parameter sets the number of Rows in the table.</p><p><strong>columnBuilder</strong>: It’s a function that helps define the layout and functionality of each column in the table. It takes an integer as a parameter, and it returns a TableSpan, which structures and configures the columns.</p><p><strong>rowbuilder</strong>: Similar to columnBuilder, this function defines the layout and behavior for each row in the TableView.</p><p><strong>cellBuilder</strong>: It handles the layout of each cell within the table. It takes TableVicinity parameter containing the row and column indices for a specific cell. This helps you customize the appearance and behavior of individual cells in your table.</p><p>Run the above code and you’ll see the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*52R_GtvShtz-y_CCO-ZGnA.png" /></figure><p>Now, let’s study the features that the TableView.builder offers! So, let’s see how to customize, and control the TableView and add more functionality.</p><h3>TableSpan</h3><p>TableSpan represents a row or a column within the TableView.</p><h4>Add a border</h4><pre>TableSpan buildTableSpan(int index) {<br>  TableSpanDecoration decoration = const TableSpanDecoration(<br>      border: TableSpanBorder(<br>          trailing: BorderSide(color: Colors.black),<br>          leading: BorderSide(color: Colors.black)));<br>  return  TableSpan(<br>      extent: const FixedTableSpanExtent(100),<br>      foregroundDecoration: decoration);<br>}</pre><p>TableSpanDecoration class is used to specify the decoration for a TableSpan. We can add a border to TableSpan through border parameters from TableSpanBorder class which has trailing and leading properties representing the border on the row&#39;s right and left sides and the Column&#39;s ups and downsides.</p><h4>Add color</h4><pre>TableSpan buildTableSpan(int index) {<br>  TableSpanDecoration decoration =  TableSpanDecoration(<br>      color: index == 0 ? Colors.grey[300] : null,<br>      border: const TableSpanBorder(<br>          trailing: BorderSide(color: Colors.black),<br>          leading: BorderSide(color: Colors.black)));<br>  return  TableSpan(<br>      extent: const FixedTableSpanExtent(100),<br>      backgroundDecoration: decoration);<br>}</pre><p>The color property within the TableSpanDecoration is used to set the color for TableSpan.</p><p>Run the code and the output will look like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*V_qunhui1_WKEMzxPegQfA.png" /></figure><p>Because,</p><ul><li>In a TableView, decorations are painted in a specific order.</li><li>backgroundDecoration of the mainAxis (rows or columns that are the primary axis) is painted first.</li><li>Then, decorations from other axes are painted.</li><li>Next, the individual cell content within the span is painted.</li><li>Finally, any specified foregroundDecoration is painted on top of the content.</li></ul><p>Here the default axis is Axis.vertical so, columns are painted first and then the rows are painted and the border is overlapped by row decoration so, let&#39;s add a border to the foreground Decoration.</p><pre>TableSpan buildTableSpan(int index) {<br>  TableSpanDecoration foreGroundDecoration = const TableSpanDecoration(<br>      border: TableSpanBorder(<br>          trailing: BorderSide(color: Colors.black),<br>          leading: BorderSide(color: Colors.black)));<br>  TableSpanDecoration backGroundDecoration = TableSpanDecoration(<br>    color: index == 0 ? Colors.grey[300] : null,<br>  );<br>  return TableSpan(<br>      extent: const FixedTableSpanExtent(100),<br>      backgroundDecoration: backGroundDecoration,<br>      foregroundDecoration: foreGroundDecoration);<br>}</pre><p>Adding a border in the foreground Decoration ensures that it’s rendered on top of the cell content in the TableView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*vlkRYW_1dBlm3YcELYoyMA.png" /></figure><h4>TableSpan.extent</h4><p>It represents the height of the row and the width of the column. There are four types of the TableSpanExtent.</p><p><strong>1. FixedTableSpanExtent</strong></p><p>A Span with a fixed [pixels].</p><pre>extent: const FixedTableSpanExtent(50),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*wLpmofUOSF-JnS0UEisEoQ.png" /></figure><p><strong>2. FractionTableSpanExtent</strong></p><p>It specifies the span extent as a fraction of the viewport extent. It is the same as Expanded widget which occupies space according to the provided fraction.</p><pre>extent: const FractionalTableSpanExtent(0.5),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*RGjxi7TjVcPVnu5K8HOfjw.png" /></figure><p><strong>3. RemainingTableSpanExtent</strong></p><p>It specifies that the span should occupy the remaining space in the viewport.</p><pre>TableSpan buildColumnSpan(int index) {<br>  TableSpanDecoration decoration =  const TableSpanDecoration(<br>      border: TableSpanBorder(<br>          trailing: BorderSide(color: Colors.black),<br>          leading: BorderSide(color: Colors.black)));<br>  return TableSpan(<br>      extent: index==0? FixedTableSpanExtent(100):RemainingTableSpanExtent(), backgroundDecoration: decoration);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*6GCpkx79AO1Sttex4DHATg.png" /></figure><p><strong>4. CombiningTableSpanExtent</strong></p><p>It takes two extents as a parameter and runs the result of these two extents through a combiner function.</p><pre>TableSpan buildRowSpan(int index) {<br>    TableSpanExtent extent1 = FixedTableSpanExtent(100);<br>    TableSpanExtent extent2 = FixedTableSpanExtent(100);<br>    double combiner(double value1, double value2) {<br>      return value1 + value2;<br>    }<br><br>    TableSpanDecoration foreGroundDecoration = const TableSpanDecoration(<br>        border: TableSpanBorder(<br>            trailing: BorderSide(color: Colors.black),<br>            leading: BorderSide(color: Colors.black)));<br>    TableSpanDecoration backGroundDecoration = TableSpanDecoration(<br>      color: index == 0 ? Colors.grey[300] : null,<br>    );<br>    if (index == 1) {<br>      return TableSpan(<br>          extent: CombiningTableSpanExtent(extent1, extent2, combiner),<br>          backgroundDecoration: backGroundDecoration,<br>          foregroundDecoration: foreGroundDecoration);<br>    }<br>    return TableSpan(<br>        extent: const FixedTableSpanExtent(100),<br>        backgroundDecoration: backGroundDecoration,<br>        foregroundDecoration: foreGroundDecoration);<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*F5jEUlJ6H_D1A9RfznEsBg.png" /></figure><h4>void Function(PointerEnterEvent)? onEnter</h4><p>It Triggers when a mouse pointer, with or without a button pressed, has entered the row or column described by this span.</p><pre>void Function(PointerEnterEvent)? onEnter</pre><h4>void Function(PointerExitEvent)? onExit</h4><p>It triggers when a mouse pointer, with or without a button pressed, has exited the row or column described by this span.</p><pre>void Function(PointerExitEvent)? onExit</pre><h4>recognizerFactories</h4><pre>recognizerFactories: &lt;Type, GestureRecognizerFactory&gt;{<br>  TapGestureRecognizer:<br>  GestureRecognizerFactoryWithHandlers&lt;TapGestureRecognizer&gt;(<br>        () =&gt; TapGestureRecognizer(),<br>        (TapGestureRecognizer t) {<br>          t.onTapDown=(TapDownDetails tapdownDetails){<br>            print(tapdownDetails.localPosition);<br>          };<br>          t.onTapUp=(TapUpDetails tapupDetails){<br>            print(tapupDetails.localPosition);<br>          };<br>        }   <br>  ),<br>},</pre><p>recognizerFactories is a map where the keys are types of gestures and the values are instances of GestureRecognizerFactory.</p><p>The GestureRecognizerFactoryWithHandlers takes two arguments.<br>A function that returns an instance of TapGestureRecognizer when called and a callback function that initializes the TapGestureRecognizer and sets the event handler to handle specific event details.</p><h4>Add a Padding</h4><p>The padding property is used to add padding for each row and column.</p><pre>padding: TableSpanPadding(leading: 10),</pre><h4>Add more columns &amp; rows to the UI</h4><p>Let’s show more data from the Employee class like email and role in the TableView.</p><pre>  Widget addText(TableVicinity vicinity) {<br>    if (vicinity.yIndex == 0 &amp;&amp; vicinity.xIndex == 0) {<br>      return const Text(&quot;Index&quot;);<br>    } else if (vicinity.yIndex == 0 &amp;&amp; vicinity.xIndex == 1) {<br>      return const Text(&quot;name&quot;);<br>    } else if (vicinity.yIndex == 0 &amp;&amp; vicinity.xIndex == 2) {<br>      return const Text(&quot;Email&quot;);<br>    } else if (vicinity.yIndex == 0 &amp;&amp; vicinity.xIndex == 3) {<br>      return const Text(&quot;Role&quot;);<br>    } else if (vicinity.xIndex == 0) {<br>      return Text(employees[vicinity.yIndex - 1].id);<br>    } else if (vicinity.xIndex == 1) {<br>      return Text(employees[vicinity.yIndex - 1].name);<br>    } else if (vicinity.xIndex == 2) {<br>      return Text(employees[vicinity.yIndex - 1].email);<br>    } else if (vicinity.xIndex == 3) {<br>      return Text(employees[vicinity.yIndex - 1].role);<br>    }<br>    return Text(&quot;&quot;);<br>  }<br>...<br><br>      body: TableView.builder(<br>          mainAxis: Axis.horizontal,<br>          columnCount: 4,<br>          rowCount: 21,<br>          columnBuilder: buildColumnSpan,<br>          rowBuilder: buildTableSpan,<br>          cellBuilder: (BuildContext context, TableVicinity vicinity) {<br>            return Center(child: addText(vicinity));<br>          }),<br>...<br><br>TableSpan buildColumnSpan(int index) {<br>  TableSpanDecoration decoration = const TableSpanDecoration(<br>      border: TableSpanBorder(<br>          trailing: BorderSide(color: Colors.black),<br>          leading: BorderSide(color: Colors.black)));<br>  if (index == 2) {<br>    return TableSpan(<br>      extent: const RemainingTableSpanExtent(),<br>      backgroundDecoration: decoration,<br>    );<br>  } else if (index == 3) {<br>    return TableSpan(<br>      extent: const FractionalTableSpanExtent(0.5),<br>      backgroundDecoration: decoration,<br>    );<br>  }<br>  return TableSpan(<br>      extent: FixedTableSpanExtent(100), backgroundDecoration: decoration);<br>}</pre><p>and the output is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*eEycuGiuNCwHMjwQHwtZ3g.gif" /></figure><h4>Pinning the rows and columns</h4><p>To pin a specific number of rows and columns persistently appearing at the edges of the TableView viewport.</p><pre>TableView.builder(<br>...<br>    pinnedRowCount: 1,<br>    pinnedColumnCount: 1,<br>   ),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*p6v9iWhRhiWV1fLgLF0LvA.gif" /></figure><h4>ScrollableDetail</h4><p>The ScrollableDetail allows specific configurations for the vertical and horizontal scroll behavior of the widget.</p><pre>verticalDetails: ScrollableDetails.vertical(<br>  reverse: true,<br>  controller: verticalController,<br>  physics: const AlwaysScrollableScrollPhysics(),<br>  decorationClipBehavior: Clip.hardEdge<br>),</pre><p>The verticalDetails within the ScrollableDetails allows specific configuration for the vertical scroll behavior of a widget. It encapsulates various properties.</p><pre>verticalDetails: ScrollableDetails.vertical(<br>  reverse: true,<br>  controller: verticalController,<br>  physics: const AlwaysScrollableScrollPhysics(),<br>  decorationClipBehavior: Clip.hardEdge,<br>)</pre><p>Here’s a breakdown of the properties:</p><ul><li><strong>reverse</strong>: When set to true, the content within the widget scrolls in the opposite direction.</li><li><strong>controller</strong>: The ScrollController assigned to manage and control the scrolling behavior. It allows you to scroll to specific positions or listen to the scroll offset changes.</li><li><strong>physics</strong>: Determines the behavior of the scrolling physics.</li><li><strong>decorationClipBehavior</strong>: Specifies the clipping behavior for the scrollable area&#39;s decorations</li></ul><h4>cacheExtent</h4><pre>cacheExtent: 200,</pre><p>Similar to ListView, cacheExtent is the size of the area drawn before being in the visible part of the screen.</p><h4>DiagonalDragBehavior</h4><p>This enum allows developers to specify how diagonal scrolling should be handled using kTouchSlop.</p><h3>Conclusion</h3><p>In this tutorial, we learned how to implement tableView in Flutter using the <strong>two_dimensional_scrollable</strong> in Flutter and there is much more we can do with this and add more functionality using it. This was a small introduction to the TableView in Flutter from my side.</p><p>I hope this article has given you enough information to add TableView to your Flutter projects. If you have any questions or feedback, feel free to leave them in the comments section.</p><p>You can find the full source code <a href="https://gist.github.com/cp-sneha-s/d2375b2a624f5650fa3836a84805b15f"><strong>here</strong></a>.</p><p>Happy coding! 👋</p><h3>Useful Articles</h3><ul><li><a href="https://blog.canopas.com/exploring-flutters-new-sliver-api-a-comprehensive-guide-a750d4d212b7">Exploring Flutter’s new Sliver API: A Comprehensive Guide</a></li><li><a href="https://blog.canopas.com/flutter-animations-made-fun-a-smiley-that-reacts-to-your-every-move-9ebfb0a0657f">Flutter Animations Made Fun: A Smiley That Reacts to Your Every Move</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedback and suggestions are most welcome, add them in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8b0fe703614" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/how-to-implement-2d-scrollable-tableview-in-flutter-a8b0fe703614">How to Implement 2D Scrollable TableView in Flutter</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Flutter’s new Sliver API: A Comprehensive Guide]]></title>
            <link>https://medium.com/canopas/exploring-flutters-new-sliver-api-a-comprehensive-guide-a750d4d212b7?source=rss-f50ffffc2644------2</link>
            <guid isPermaLink="false">https://medium.com/p/a750d4d212b7</guid>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[stickyheader]]></category>
            <category><![CDATA[flutter-api]]></category>
            <category><![CDATA[slivers]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Sneha S]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 09:43:04 GMT</pubDate>
            <atom:updated>2023-10-27T13:50:12.423Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Explore the new sliver API, introduced in Flutter 3.13</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Icbih7V5BmcuZperl1Istg.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3>Background</h3><p>Up until now, there is no way to group slivers together and render them as single sliver in customScrollview. What if we needed to apply different padding to individual groups of slivers? or what if you wanted to create a vertically scrollable list of slivers side by side, much like using a raw widget?</p><p>Well, the release of Flutter 3.13, introduces two different widgets, SliverMainAxisGroup and SliverCrossSxisGroup to group slivers in the main-axis and cross-axis respectively. There are new features and improvements when it comes to scrolling with this new API and the best part? you can easily create one of my favorite— sticky headers.</p><p>In this article, I’ll give you a basic guide on these new slivers and then play with slivers to create a demo UI.</p><p><strong><em>What we’re going to implement?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*5ZqjclWyGvD5FsZJgdnnEA.gif" /></figure><h3>Table of contents</h3><pre>· <a href="#0d95">What is sliver?</a><br>· Types:<br>  · <a href="#dba3">SliverMainAxisGroup</a><br>  · <a href="#5bff">SliverCrossAxisGroup</a><br>· <a href="#2f2d">SliverCrossAxisExpanded</a><br>· <a href="#7cf3">SliverConstrainedCrossAxis</a><br>· <a href="#7233">Implement Demo UI</a><br>  · <a href="#43f1">Create a Basic UI</a><br>  · <a href="#e28c">Add CircleAvatar</a><br>  · <a href="#710f">Move CircleAvatar</a><br>  · <a href="#ee6a">Resize CircleAvata</a>r<br> · <a href="#6ee3">Conclusion</a></pre><h3>Sponsored</h3><p>We are what we repeatedly do. Excellence, then, is not an act, but a habit. Try out <a href="https://justly.life/dl"><strong>Justly</strong></a><strong> </strong>and start building your habits today!</p><p><a href="https://justly.life/dl?source=post_page-----9ebfb0a0657f--------------------------------">Justly: Habits, Goals, Journal</a></p><h3>What is a sliver?</h3><blockquote>A sliver is a portion of a scrollable area that you can define to behave in a special way. You can use slivers to achieve custom scrolling effects, such as elastic scrolling.</blockquote><p>To put it simply, slivers are like a more detailed way to control how things scroll.</p><p>You can think of <strong>slivers</strong> as a lower-level interface, providing finer-grained control on implementing scrollable areas. Because slivers can lazily build each item just as it scrolls into view, slivers are particularly useful for efficiently scrolling through large numbers of children.</p><p>All of the scrollable views you use, like ListView and GridView, are actually implemented using Slivers.</p><p>Let’s look at the types of the SliversGroup there are:</p><ol><li>SliverCrossAxisGroup</li><li>SliverMainAxisGroup</li></ol><h3>SliverMainAxisGroup</h3><p>A sliver that places multiple sliver children in a linear array along the main axis, one after another. To use SliverMainAxisGroup, simply pass in the slivers. For example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*36rL8rMZVnb__CHaFnJuSA.gif" /></figure><p>The general format for the code is</p><pre>CustomScrollView(<br>          slivers: [<br>            SliverMainAxisGroup(slivers: [<br>              SliverPersistentHeader(<br>                delegate: HeaderDelegate(title: &#39;SliverList&#39;),<br>                pinned: true,<br>              ),<br>              SliverPadding(<br>                padding: EdgeInsets.all(16),<br>                sliver: decoratedSliverList(),<br>              ),<br>            ]),<br>            SliverMainAxisGroup(slivers: [<br>              SliverPersistentHeader(<br>                delegate: HeaderDelegate(title: &#39;SliverGrid&#39;),<br>                pinned: true,<br>              ),<br>              sliverGrid(10)<br>            ]),<br>          ],<br>        ),<br><br><br><br> Widget decoratedSliverList() {<br>    return DecoratedSliver(<br>      position: DecorationPosition.background,<br>      decoration: BoxDecoration(<br>        color: Colors.yellow,<br>      ),<br>      sliver: SliverList.separated(<br>        itemBuilder: (_, int index) =&gt;<br>            Container(height: 50, child: Center(child: Text(&#39;Item $index&#39;))),<br>        separatorBuilder: (_, __) =&gt; Divider(),<br>        itemCount: 15,<br>      ),<br>    );<br>  }<br>}</pre><p>No need to explain, right?? here we added SliverMainAxisGroup to group sliver elements sequentially along the main Axis. Each SliverMainAxisGroup contains SliverPersistentHeader with a delegate that creates a <strong>sticky header</strong>. The pinned: true property set headers to be fixed at the top during scrolling.</p><p>Flutter introduces DecoratedSliver, which is similar to DecoratedBox for sliver to paint a decoration either before or after its child paints.</p><h3>SliverCrossAxisGroup</h3><p>It’s a widget that arranges a list of slivers in a linear array along the cross-axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*DoFFvJiO3766rAerDIaYNA.png" /></figure><p>The picture looks quite simple and its implementation is as easy as it looks…😊</p><pre>     SliverCrossAxisGroup(slivers: [<br>              SliverPadding(<br>                  padding: const EdgeInsets.all(16),<br>                  sliver: decoratedSliverList()),<br>              SliverPadding(<br>                  padding: const EdgeInsets.all(16),<br>                  sliver: decoratedSliverList()),<br>              SliverPadding(<br>                  padding: const EdgeInsets.all(16),<br>                  sliver: decoratedSliverList()),<br>            ]),</pre><p>Well, this widget organizes these slivers in a linear array along the cross-axis, similar to how row handle their children. The widget will take in a list of <strong>slivers</strong>, and by default, each widget will be assigned equal cross-axis constraints.</p><p>But what if we want to divide up the cross-axis constraint in a different way like row and column divides up space? That’s where Flutter introduces two more widgets SliverCrossAxisExpanded and SliverConstrainedCrossAxis.</p><h3>SliverCrossAxisExpanded</h3><p>The SliverCrossAxisExpanded widget is similar to Expanded widget for row and columnto fill available along the cross-axis. The flex property decides how much space should be taken.</p><pre>        SliverCrossAxisGroup(slivers: [<br>              SliverPadding(<br>                  padding: const EdgeInsets.all(16),<br>                  sliver: decoratedSliverList()),<br>              SliverCrossAxisExpanded(<br>                flex: 2,<br>                sliver: SliverPadding(<br>                    padding: const EdgeInsets.all(16),<br>                    sliver: decoratedSliverList()),<br>              ),<br>              SliverPadding(<br>                  padding: const EdgeInsets.all(16),<br>                  sliver: decoratedSliverList()),<br>            ]),</pre><p>The output is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*GHNsrE80tETmpNvmwL56iw.png" /></figure><h3>SliverConstrainedCrossAxis</h3><p>The SliverConstrainedCrossAxis is similar to the ConstrainedBox widget that allows you to constrain the cross-axis of a sliver.</p><p>The SliverConstrainedCrossAxis takes a mxExtent parameter and used as the cross-axis extent of the SliverConstraints passed to the sliver child. The maxExtent should be a non-negative value.</p><pre> SliverCrossAxisGroup(slivers: [<br>              SliverPadding(<br>                  padding: const EdgeInsets.all(16),<br>                  sliver: decoratedSliverList()),<br>              SliverCrossAxisExpanded(<br>                flex: 2,<br>                sliver: SliverPadding(<br>                    padding: const EdgeInsets.all(16),<br>                    sliver: decoratedSliverList()),<br>              ),<br>              SliverConstrainedCrossAxis(<br>                maxExtent: 200,<br>                sliver: SliverPadding(<br>                    padding: const EdgeInsets.all(16),<br>                    sliver: decoratedSliverList()),<br>              ),<br>            ]),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*Xah9iXjLlWpGisnRLAmGRQ.png" /></figure><h3>Implement Demo UI</h3><p>All right, It’s time to have some fun with slivers!! 🍻</p><p>We are going to implement this UI inspired by <a href="https://github.com/android/compose-samples/tree/main/Jetsnack">JetSnack</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*5ZqjclWyGvD5FsZJgdnnEA.gif" /></figure><p>So, let’s first observe the behavior. Well, it has two pinned Appbars that collapse one after the other, followed by scrolling through the recipe screen.</p><h4>Create a Basic UI</h4><p>It’s a basic UI for the screen.</p><pre>class ChocolatePage extends StatefulWidget {<br>  const ChocolatePage({super.key});<br><br>  @override<br>  State&lt;ChocolatePage&gt; createState() =&gt; _ChocolatePageState();<br>}<br><br>class _ChocolatePageState extends State&lt;ChocolatePage&gt; {<br>  final maxHeight = 600;<br>  final minHeight = 250;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: CustomScrollView(<br>        slivers: [<br>          SliverPersistentHeader(<br>            pinned: true,<br>            floating: true,<br>            delegate: SliverAppbarDelegate(<br>                maxHeight: maxHeight / 2,<br>                minHeight: minHeight / 2,<br>                child: Container(<br>                  decoration: const BoxDecoration(<br>                      gradient: LinearGradient(<br>                          colors: [<br>                            Color(0xff4b5de0),<br>                            Color(0xff1e0c98),<br>                          ]<br>                      )<br>                  ),<br>                )<br>            ),<br>          ),<br>        SliverPersistentHeader(<br>                pinned: true,<br>                delegate: SliverAppbarDelegate(<br>                    maxHeight: maxHeight / 2,<br>                    minHeight: minHeight / 2,<br>                    child: Container(<br>                      color: Colors.white,<br>                      child: const Padding(<br>                        padding: EdgeInsets.only(left: 16.0,bottom: 16),<br>                        child: Column(<br>                          crossAxisAlignment: CrossAxisAlignment.start,<br>                          children: [<br>                            Spacer(),<br>                            Text(&#39;Chips&#39;,style: TextStyle(fontSize: 40,fontWeight: FontWeight.w700),),<br>                            SizedBox(height: 20,),<br>                            Text(&#39;\$12.99 &#39;,style: TextStyle(color:Color(0xff1e0c98),fontWeight: FontWeight.w600,fontSize: 30),)<br>                          ],<br>                        ),<br>                      ),<br>                    )<br>                ),<br>              ),<br>          recipeDetail()<br>        ],<br>      ),<br>    );<br>  }<br>}<br><br>class SliverAppbarDelegate extends SliverPersistentHeaderDelegate {<br>  final double maxHeight;<br>  final double minHeight;<br>  final Widget child;<br><br>  SliverAppbarDelegate(<br>      {Key? key, required this.maxHeight, required this.minHeight, required this.child});<br><br><br>  @override<br>  Widget build(BuildContext context, double shrinkOffset,<br>      bool overlapsContent) =&gt; SizedBox.expand(child: child,);<br><br>  @override<br>  double get maxExtent =&gt; maxHeight;<br><br>  @override<br>  double get minExtent =&gt; minHeight;<br><br>  @override<br>  bool shouldRebuild(SliverAppbarDelegate oldDelegate) {<br>    return maxHeight != oldDelegate.maxHeight ||<br>        minHeight != oldDelegate.minHeight ||<br>        child != oldDelegate.child;<br>  }<br><br>}</pre><p>It is self-explanatory, right? We have CustomScrollView with two SliverpersistentHeader, each with the pinned and floating parameter set to <strong>true</strong>, to create a pinned app bar while scrolling, and below the app bar, there is a recipe detail screen that contains detailed content of the screen.</p><p>Let’s see what it looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*BZbxuDoy6UIHSgAmvNx5WQ.png" /></figure><h4>Add CircleAvatar</h4><p>Okay, now let’s add CircleAvatar.</p><pre>final double initialRadius=170;<br><br>@override<br>Widget build(BuildContext context) {<br>  return Scaffold(<br>    body: Stack(<br>      children: [<br>        CustomScrollView(<br>          ...<br>        ),<br>        Positioned(<br>          top: (maxHeight/2)-initialRadius,<br>            left: MediaQuery.of(context).size.width/2-initialRadius,<br>            child: CircleAvatar(<br>              backgroundImage: AssetImage(&#39;assets/chocolate.jpeg&#39;),<br>              radius: initialRadius,<br>            ))<br>      ],<br>    ),<br>  );<br>}</pre><p>No need for any explanation. CircleAvatar is positioned at the center between both appbars and the radius is set to 170.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*AJi0cj38QtlRo0maUodFGQ.png" /></figure><p>Okay, great 👍.</p><h4>Move CircleAvatar</h4><p>Now let’s move the CircleAvater with scrolling.</p><pre>class _ChocolatePageState extends State&lt;ChocolatePage&gt; {<br>  late final ScrollController scrollController;<br>  double scrollPercentage=0.0;<br><br><br>  final double maxHeight = 600;<br>  final double minHeight = 250;<br>  final double initialRadius=170;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    scrollController= ScrollController();<br>    scrollController.addListener(onScroll);<br>  }<br><br>  void onScroll() {<br>    double offset= scrollController.offset;<br>    double  maxOffset = 350;<br>    setState(() {<br>      scrollPercentage=(offset/maxOffset).clamp(0.0, 1.0);<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Stack(<br>        children: [<br>          CustomScrollView(<br>            ...<br>          ),<br>          Positioned(<br>            top: ((maxHeight/2)-initialRadius)*(1-scrollPercentage),<br>              right: (MediaQuery.of(context).size.width/2-initialRadius)*(1-scrollPercentage),<br>              child: CircleAvatar(<br>                backgroundImage: AssetImage(&#39;assets/chocolate.jpeg&#39;),<br>                radius: initialRadius,<br>              ))<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>Here, added ScrollController to monitor the scroll position. Calculates the scrollPercentage as the ratio of the current scrolloffset to the maxOffset that is the difference between maxHeight and minHeight of the app bar, clamped between 0.0 to 1.0. This scrollPercentage represents how far the user has scrolled in relation to the maximum scroll distance and updates the position of the CircleAvatar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*aw7TcdOJAcie2IoPVt6Onw.gif" /></figure><h4>Resize CircleAvatar</h4><p>Almost done, It’s time to resize CircleAvatar</p><pre>final double initialRadius=130;<br>final double finalRadius= 60;<br><br> Transform.scale(<br>      scale: (initialRadius-(initialRadius-finalRadius)*scrollPercentage)/100,<br>      child: CircleAvatar(<br>           backgroundImage: AssetImage(&#39;assets/chocolate.jpeg&#39;),<br>           radius: initialRadius,<br>        ),<br>     )</pre><p>Pretty easy 😊, isn’t it?? Here, we have wrapped the CircleAvatar with Transform.scale to resize it based on the scrollPercentage. Simply, as the user scrolls, the radius decreases from initialRadius to finalRadius.</p><p>Now, run the app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*oF_lX6AaP4gq-AzbYQJD0w.gif" /></figure><p>It&#39;s done!! Hold on, we have one issue here. The recipe detail area begins to move slightly before the second app bar starts to collapse.</p><p>With SliverMainAxisGroup, it takes it as a part of the same <strong>sliver group,</strong> causing them to scroll and stay positioned behind the first SliverPersistentHeader. So, let&#39;s group second appbar and recepiDetail with SliverMainAxisGroup and set a static height for the app bar while collapsing.</p><pre>CustomScrollView(<br>  slivers: [<br>    SliverPersistentHeader(<br>             minHeight: 100<br>    ),<br>    SliverMainAxisGroup(<br>      slivers: [<br>       SliverPersistentHeader(<br>              minHeight: 250,<br>     ),<br>       recipeDetail()<br>    ],<br>   ),<br>  ],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*5ZqjclWyGvD5FsZJgdnnEA.gif" /></figure><p>Cool 👌…We are done!!!</p><h3>Conclusion</h3><p>In this article, we have explored the new Sliver API in Flutter 3.13 and implemented a demo UI to play with Sliver. This was a small introduction to new Slivers on UserInteraction from my side, and you can modify this code according to your requirements.</p><p>Thank you !!!</p><p>The source code is available <a href="https://gist.github.com/cp-sneha-s/0997f69db4d167730f59dda77c738571"><strong>here</strong></a><strong>.</strong></p><h3>Useful Articles</h3><ul><li><a href="https://blog.canopas.com/flutter-customizing-serialization-and-deserialization-with-json-serializable-db17e3aa90b0">Flutter — Customizing Serialization and Deserialization with json_serializable</a></li><li><a href="https://blog.canopas.com/how-to-maintain-the-state-of-bottomnavigationbar-across-tabs-528b3699f78b">How to Maintain the state of BottomNavigationBar across tabs</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedback and suggestions are most welcome, add them in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a750d4d212b7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/exploring-flutters-new-sliver-api-a-comprehensive-guide-a750d4d212b7">Exploring Flutter’s new Sliver API: A Comprehensive Guide</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Transform Dart Streams: A Basic Guide to Stream Operators]]></title>
            <link>https://medium.com/canopas/how-to-transform-dart-streams-a-basic-guide-to-stream-operators-c33f17c1aaf9?source=rss-f50ffffc2644------2</link>
            <guid isPermaLink="false">https://medium.com/p/c33f17c1aaf9</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Sneha S]]></dc:creator>
            <pubDate>Wed, 26 Jul 2023 09:53:11 GMT</pubDate>
            <atom:updated>2024-04-28T12:51:09.484Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explores Some of the Basic Stream Operators to Transform the Stream.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iTS3t7XEy14aQhRqCRxbg.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><p>According to the Flutter documentation, streams provide an essential feature for handling asynchronous sequences of data. It provides a way to handle and process a continuous flow of data, where each event can be asynchronously received and processed.</p><p>To use the streams to their full potential, we can use stream operators. These operators are the methods that allow us to transform, filter, process, and combine stream data efficiently.</p><p>In this article, we’ll take a tour of some operators/methods with examples that are available in the Stream class.</p><h3>Table of contents</h3><pre>  1. <a href="#ec22">asyncMap</a><br>  2. <a href="#f59e">asyncExpand</a><br>  3. <a href="#fca5">StreamTransformer</a><br>  4. <a href="#a910">pipe</a><br>  5. <a href="#da52">singleWhere</a><br>  6. <a href="#de66">cast</a><br>  7. <a href="#9d3a">distinct</a><br>  8. <a href="#d977">skip</a><br>· <a href="#4c9c">Conclusion</a></pre><h3>Sponsored</h3><p>Positive thinking leads to positive outcomes. Try out <a href="https://justly.life/dl"><strong>Justly</strong></a><strong>, </strong>build good habits, and start thinking positively today!</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>1. asyncMap</h3><pre>Stream&lt;E&gt; asyncMap&lt;E&gt;(FutureOr&lt;E&gt; Function(List&lt;String&gt;) convert)</pre><p>The asyncMap operator takes a source stream and creates a new stream by mapping each event of the source stream to a new event. It behaves similarly to a map, but with a mapping function convert that can return a Future and the stream waits for that Future to complete before emitting the result.</p><pre>void main()async {<br>  final dataStream= Stream.fromIterable([1,2,3,4,5]);<br>  final stream= dataStream.asyncMap((data)async=&gt;processData(data));<br>}<br><br>Future&lt;int&gt; processData(int data) async {<br>  // Simulate an asynchronous operation<br>  await Future.delayed(Duration(seconds: data));<br>  print(&#39;ProcessedData: $data&#39;);<br>  return data;  <br>}<br><br>//prints data with 1 second interval<br>ProcessedData: 1<br>ProcessedData: 2<br>ProcessedData: 3<br>ProcessedData: 4<br>ProcessedData: 5</pre><p>ayncMap is particularly useful when performing some asynchronous API Calls on each event of a stream.</p><h3>2. asyncExpand</h3><pre>Stream&lt;E&gt; asyncExpand&lt;E&gt;(Stream&lt;E&gt;? Function(List&lt;String&gt;) convert)</pre><p>The asyncExpand operator applies an asynchronous mapping function convert to each event of the source stream, where the mapping function returns a new stream.</p><pre><br>Stream&lt;List&lt;int&gt;&gt; getNestedStream() async* {<br>  for (int i = 1; i &lt;= 3; i++) {<br>    await Future.delayed(Duration(seconds: 1));<br>    yield List&lt;int&gt;.generate(i, (index) =&gt; index + 1);<br>  }<br>}<br><br>void main() {<br>  getNestedStream()<br>      .asyncExpand((nestedList) =&gt; Stream.fromIterable(nestedList))<br>      .listen((value) {<br>    print(value); // Prints: 1, 1, 2, 1, 2, 3<br>  });<br>}</pre><p>asyncExpand is useful when you want to transform each event into a stream and then combine those streams into a single output stream, flattening any nested structure. This is useful when you want to perform operations on each event, such as making asynchronous API calls, database queries, or performing computationally expensive calculations.</p><p>However, it’s important to note that the result stream will only move on to the next event in the source stream if the substream of the first event has closed.</p><h3>3. StreamTransformer</h3><pre>Stream&lt;S&gt; transform&lt;S&gt;(StreamTransformer&lt;List&lt;String&gt;, S&gt; streamTransformer)</pre><p>It simply transforms a stream. You might find yourself using the streamTransformer class multiple times. When you have a stream and want to apply specific transformations or operations on the emitted data, you can use StreamTansformer.</p><p>To use StreamTransformer, we have to provide the input and output type of the transformation and implement the transformation logic within the StreamTransformer’s bind method. the bind method is called when the stream.tansform method is invoked on a stream within the StreamTransformer.</p><pre>void main() {<br>  final sourceStream = Stream.fromIterable([1, 2, 3, 4]);<br>  final transformer = StreamTransformer&lt;int, String&gt;.fromHandlers(<br>    handleData: (data, sink) {<br>      if (data % 2 == 0) {<br>        sink.add(&#39;Even: $data&#39;);<br>      } else {<br>        sink.add(&#39;Odd: $data&#39;);<br>      }<br>    },<br>  );<br><br>  final transformedStream = sourceStream.transform(transformer);<br><br>  transformedStream.listen((data) {<br>    print(data);<br>  });<br>}<br><br>//Prints:<br>Odd: 1<br>Even: 2<br>Odd: 3<br>Even: 4</pre><p>StreamTransformer provides a way to customize the behavior of the stream, apply a transformation, perform validation, and handle errors.</p><h3>4. pipe</h3><pre>Future&lt;dynamic&gt; pipe(StreamConsumer&lt;List&lt;String&gt;&gt; streamConsumer)</pre><p>The pipe() method in streams is commonly used for efficiently transferring data from one stream to another.</p><pre>import &#39;dart:async&#39;;<br><br>void main() {<br>  final sourceStream = Stream.fromIterable([&#39;How&#39;, &#39;are&#39;, &#39;you&#39;]);<br>  final destinationStreamController = new StreamController&lt;String&gt;();   <br>  <br>sourceStream.transform(_capitalizeTransformer()).pipe(destinationStreamController);<br><br>destinationStreamController.stream.listen((data) {<br>    print(data); // Prints: HOW, ARE, YOU<br>  });<br>}<br><br>StreamTransformer&lt;String, String&gt; _capitalizeTransformer() {<br>  return StreamTransformer&lt;String, String&gt;.fromHandlers(<br>    handleData: (data, sink) {<br>      final capitalizedData = data.toUpperCase();<br>      sink.add(capitalizedData);<br>    },<br>  );<br>}</pre><p>Yes, we can do it by calling destinationStreamController.add() , but the destinationStreamController will still be open after the stream is done but sourceStream.pipe(destinationStreamCotroller) will close() the destinationStreamController once the stream is finished.</p><p>pipe() enables you to compose complex data processing pipelines by connecting multiple streams together. You can transform, filter, or manipulate the data in each stream using various stream operators and transformers, and then pass the transformed data to the next stream in the pipeline using pipe().</p><h3>5. singleWhere</h3><pre>Future&lt;List&lt;String&gt;&gt; singleWhere(bool Function(List&lt;String&gt;) test, {List&lt;String&gt; Function()? orElse})</pre><p>The singleWhere method is used in streams to find a single element that matches a specified condition. It searches for the first element that satisfies the given condition and returns it, If no matching element is found or if multiple elements match the condition, it throws an error.</p><pre>void main() async{<br>  final stream = Stream.fromIterable([<br>    {&#39;name&#39;: &#39;Alice&#39;, &#39;age&#39;: 25},<br>    {&#39;name&#39;: &#39;Bob&#39;, &#39;age&#39;: 30},<br>    {&#39;name&#39;: &#39;Charlie&#39;, &#39;age&#39;: 35},<br>  ]);<br>  try {<br>    final person = await  stream.singleWhere((element) =&gt; element[&#39;age&#39;] == 30);<br>    print(person); // Output: {name: Bob, age: 30}<br>  } catch (e) {<br>    print(e); // Output: Bad state: No element<br>  }</pre><p>It calls data asynchronously because singleWhere needs to wait for the stream to emit the matching element, and if no match is found, it needs to wait until the stream is done emitting elements.</p><h3>6. cast</h3><pre>Stream&lt;R&gt; cast&lt;R&gt;()</pre><p>This stream is wrapped as a Stream&lt;R&gt; which checks at run-time that each data event emitted by this stream is also an instance of R.</p><p>By using cast() operator you can ensure that the events emitted by the stream are of the correct type to prevent type errors and allows you to work with the stream’s data in a type-safe manner.</p><p>At runtime, it checks each data event emitted by the stream. If an event cannot be cast to the desired type, it will be excluded from the resulting stream, or it may result in an error depending on how the stream processing is handled.</p><pre>import &#39;dart:async&#39;;<br>void main() {<br>  final numbersStream = Stream&lt;dynamic&gt;.fromIterable([1,2,3.5,4,5]);<br><br>  final transformer = StreamTransformer&lt;int, int&gt;.fromHandlers(<br>    handleData: (int, sink) {<br>      sink.add(int*2);<br>    },<br>  );<br><br>  final adaptedStream = numbersStream.cast&lt;int&gt;().transform(transformer);<br><br>    adaptedStream.listen((event) { <br>      print(event);//prints: 2 4 8 10<br>    },onError: (e,s){<br>   //if we add print here<br>    print(e.toString);  //prints TypeError: 3.5: type &#39;double&#39; is not a subtype of type &#39;int&#39;<br>    });<br>  <br>}</pre><p>Everything works <em>and</em> the type system is happy. .😊 😊 !!</p><p>The cast() operator doesn’t modify the stream. Instead, it creates a new stream that emits events of the desired type. the original stream remains unchanged, and the new stream with the desired type is used for subsequent operations.</p><h3>7. distinct</h3><pre>Stream&lt;List&lt;String&gt;&gt; distinct([bool Function(List&lt;String&gt;, List&lt;String&gt;)? equals])</pre><p>The distinct() method returns a stream with unique elements. It is useful when we need to remove duplicate elements from the stream. The distinct() method has equals parameter function that checks if the previous and current value is the same.</p><pre>void main() async {<br>  <br>  Stream&lt;Person&gt; personStream = Stream.fromIterable([<br>                                       Person( &quot;Lokesh&quot;, &quot;Gupta&quot;),<br>                                       Person( &quot;Lokesh&quot;, &quot;Gupta&quot;),<br>                                       Person( &quot;Brian&quot;, &quot;Clooney&quot;),<br>                                       Person( &quot;Brian&quot;, &quot;Clooney&quot;),<br>                                       Person( &quot;Alex&quot;, &quot;Kolen&quot;)<br>                                ]);<br>  <br>  <br>  personStream.distinct((previous, next)=&gt;<br>    previous.name==next.name &amp;&amp; previous.surname==next.surname<br>  ).listen((person)=&gt;print(person.name));//Prints: Lokesh Brian Alex<br><br>}</pre><h3>8. skip</h3><pre>Stream&lt;List&lt;String&gt;&gt; skip(int count)</pre><p>The skip(int count) method returns a stream consisting of the remaining elements after the first count elements. If the stream contains fewer than count elements, we’ll get an empty stream.</p><pre>void main() {<br>  final numbersStream = Stream&lt;int&gt;.fromIterable([1,2,3,4,5]);<br>  <br>    numbersStream.skip(2).listen((event) { <br>      print(event)<br>    },onError: (e,s){<br>      print(e.toString());<br>    });  <br>}<br>//Prints: 3 4 5 </pre><h3>Conclusion</h3><p>Streams are very helpful when you want to listen for changes in your data and react according to them and stream operators add functionality to the stream. In this article, we’ve explored a few of these operators of the stream.</p><p>So, this is all for this article. If you have any questions or feedback, feel free to leave them in the comments section.</p><p>Let’s experiment with these operators, explore their different use cases, and adapt them to fit your specific needs.</p><p>Keep Streaming..!! 👋 👋</p><h3>Useful Articles</h3><ul><li><a href="https://blog.canopas.com/how-to-use-inheritedwidget-in-flutter-5fd64ce52b66">How to Use InheritedWidget in Flutter</a></li><li><a href="https://blog.canopas.com/flutter-customizing-serialization-and-deserialization-with-json-serializable-db17e3aa90b0">Flutter — Customizing Serialization and Deserialization with json_serializable</a></li><li><a href="https://blog.canopas.com/how-to-maintain-the-state-of-bottomnavigationbar-across-tabs-528b3699f78b">How to Maintain the state of BottomNavigationBar across tabs</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedbacks and suggestions are most welcome, add them in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c33f17c1aaf9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/how-to-transform-dart-streams-a-basic-guide-to-stream-operators-c33f17c1aaf9">How to Transform Dart Streams: A Basic Guide to Stream Operators</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use InheritedWidget in Flutter]]></title>
            <link>https://medium.com/canopas/how-to-use-inheritedwidget-in-flutter-5fd64ce52b66?source=rss-f50ffffc2644------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fd64ce52b66</guid>
            <category><![CDATA[data-sharing]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[inheritedwidget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Sneha S]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 10:24:50 GMT</pubDate>
            <atom:updated>2023-06-16T11:06:05.587Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explores InheritedNotifier and InheritedModel - subclasses of InheritedWidget in Flutter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*edKL74BjjfrEo9bIlQvZ1Q.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><h3>Background</h3><p>InheritedWidget provides a way to share data across the widget tree in Flutter. It serves as a container for data that can be accessed by any descendant widget in the hierarchy. Whenever the data within the InheritedWidget changes, it triggers a rebuild of all the dependent widgets in the subtree.</p><p>However, besides InheritedWidget, there are two other subclasses, InheritedNotifier and InheritedModel, that offers unique approaches to sharing data in Flutter.</p><p>In this article, we will explore each of the subclasses and how they can be implemented by code.</p><h3>Table of contents</h3><pre>· <a href="#b3b7">What is InheritedNotifier?</a><br>  · <a href="#3ebf">Defining the Listenable class</a><br>  · <a href="#0f48">Creating InheritedNotifier Class</a><br>  · <a href="#75a7">Update the state</a><br>  · <a href="#9f41">Using the InheritedNotifier</a><br>  · <a href="#90fe">Key Points</a><br>· <a href="#b966">What is InheritedModel?</a><br>  · <a href="#f45e">Creating the InheritedModel Class</a><br>  · <a href="#f309">Using the InheritedModel<br></a>  · <a href="#86a1">Key Points</a><br>· <a href="#1ad2">Conclusion</a></pre><h3>Sponsored</h3><p>Positive thinking leads to positive outcomes. Try out <a href="https://justly.life/dl"><strong>Justly</strong></a><strong>, </strong>build good habits, and start thinking positively today!</p><p><a href="https://justly.life/dl">Justly: Habits, Goals, Journal</a></p><h3>What is InheritedNotifier?</h3><p>InheritedNotifier is a subclass of InheritedWidget that combines the capabilities of InheritedWidget and ChangeNotifier. It propagates changes from a ChangeNotifier to descendant widgets. By wrapping ChangeNotifier with InheritedNotifier, you can automatically rebuild dependent widgets whenever the ChangeNotifier triggers updates using notifyListeners().</p><p>When creating an InheritedNotifier, you need to provide a Listenable object as its notifier parameter, such as ValueNotifier for simple objects or ChangeNotifier for complex objects.</p><p>To better understand the concept, let’s implement the demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ERrL5abZ3X5cxx-xBsIKrA.gif" /></figure><h4>Defining the Listenable Class</h4><p>Create a class that is listenable to update the state.</p><pre>class User {<br>  String? name;<br>  String? age;<br><br>User({this.name = &#39;&#39;, this.age = &#39;&#39;});<br><br>}<br><br>class UserState with ChangeNotifier {<br><br>  User _user = User();<br>  User get user =&gt; _user;<br><br>  void setProfile(User updatedProfile) {<br>    _user = updatedProfile;<br>    notifyListeners();<br>  }  <br>}</pre><p>Nothing fancy right??</p><p>By extending ChangeNotifier, the UserState class becomes a listenable class that can be used with InheritedNotifier to propagate state changes to its dependants in the widget tree.</p><p>So, let’s go ahead and use this class in InheritedNotifier class.</p><h4>Creating InheritedNotifier Class</h4><pre>class UserStateNotifier extends InheritedNotifier&lt;UserState&gt; {<br>  const UserStateNotifier(<br>      {super.key, required UserState userState, required super.child})<br>      : super(notifier: userState);<br><br>  static User of(BuildContext context) {<br>    return context<br>        .dependOnInheritedWidgetOfExactType&lt;UserStateNotifier&gt;()!<br>        .notifier!<br>        .user;<br>  }<br><br>  @override<br>  bool updateShouldNotify(covariant InheritedNotifier&lt;UserState&gt; oldWidget) {<br>    return notifier!.user != oldWidget.notifier!.user;<br>  }<br>}</pre><ul><li>The of method is a static method in the UserStateNotifier class that allows us to retrieve the current user profile (User) from the nearest UserStateNotifier ancestor in the widget tree.</li><li>The updateShouldNotify method in the UserStateNotifier class is responsible for determining whether the dependents of the InheritedNotifier widget should be rebuilt or not. By implementing this method, we can optimize the rebuilding process by rebuilding only when necessary, reducing unnecessary rebuilds, and improving performance.</li></ul><p>Let’s use it in the widget tree.</p><h4>Update the state</h4><p>We have a simple screen that displays the user’s name and age.</p><p>To update the user state, simply tap on the FAB button, which will open a modal bottom sheet with two Textfields, where user can update their information by adding text.</p><pre>class HomePage extends StatelessWidget {<br>  HomePage({super.key});<br><br>  final TextEditingController _nameController = TextEditingController();<br>  final TextEditingController _ageController = TextEditingController();<br><br>  final UserState userState = UserState();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      ...<br>      floatingActionButton: FloatingActionButton.extended(<br>          onPressed: () {<br>            showModalBottomSheet(<br>                context: context,<br>                builder: (_) {<br>                  return Column(<br>                    children: [<br>                      TextField(<br>                        controller: _nameController,<br>                        decoration: const InputDecoration(<br>                            hintText: &#39;What is your name?&#39;,<br>                            border: OutlineInputBorder()),<br>                      ),<br>                      const SizedBox(height: 20,),<br>                      TextField(<br>                        controller: _ageController,<br>                        decoration: const InputDecoration(<br>                          hintText: &#39;What is your age?&#39;,<br>                          border: OutlineInputBorder(),<br>                        ),<br>                        keyboardType: TextInputType.number,<br>                      ),<br>                      ElevatedButton(<br>                          onPressed: () {<br>                            User user = User(<br>                              name: _nameController.text,<br>                              age: _ageController.text<br>                            );<br>                            userState.setProfile(user);<br>                            Navigator.pop(context);<br>                          },<br>                          child: const Text(&quot;Save&quot;))<br>                    ],<br>                  );<br>                });<br>          },<br>          label: const Text(&#39;Set Profile&#39;)),<br>    );<br>  }<br>}</pre><p>And you’re all set to go. Great job!! 👍</p><h4>Using the InheritedNotifier</h4><pre>class HomePage extends StatelessWidget {<br>....<br>  final UserState userState = UserState();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;InheritedNotifier Demo&#39;),<br>      ),<br>      body: Center(<br>        child: UserStateNotifier(<br>          userState: userState,<br>          child: Builder(builder: (context) {<br>            return Column(<br>              crossAxisAlignment: CrossAxisAlignment.start,<br>              mainAxisAlignment: MainAxisAlignment.center,<br>              children: [<br>                Text(<br>                  &#39;Name : ${UserStateNotifier.of(context).name}&#39;,<br>                  style: const TextStyle(fontSize: 20),<br>                ),<br>                Text(<br>                  &#39;Age : ${UserStateNotifier.of(context).age}&#39;,<br>                  style: const TextStyle(fontSize: 20),<br>                )<br>              ],<br>            );<br>          }),<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton.extended(<br>    ....<br>  }<br>}</pre><p>No explanation is needed!!</p><p>We can access the user information by calling UserStateNotifier.of(context), which returns the user information from the <strong>UserState </strong>class.</p><p>When you run the app, any change made through the modal bottom sheet will be reflected in real-time without the need for explicit state management calls.</p><h4>Key Points</h4><ul><li>InheritedNotifier combines the functionalities of data sharing through InheritedWidget and state management through ChangeNotifier.</li><li>InheritedNotifier is designed to work with a single ChangeNotifier object. InheritedNotifier works well for small to medium-sized applications where you need a simple and efficient way to share and update states across multiple widgets.</li><li>Similar to InheritedWidget, InheritedNotifier provides global access to the shared state, which can make encapsulation and control challenging.</li></ul><h3>What is InheritedModel?</h3><p>InheritedModel is another subclass of InheritedWidget that provides a more granular way of sharing data. With this, you can define multiple models within a single InheritedModel widget and select specific models for each descendant widget to depend on.</p><p>Let’s understand it by implementing it in the above example.</p><h4>Creating the InheritedModel Class</h4><p>Let’s define theInheritedModel class that we will name UserModel.</p><pre>class UserModel extends InheritedModel&lt;User&gt; {<br>  final User? user;<br><br>  const UserModel({super.key, required super.child, this.user});<br><br>  static User? of(BuildContext context) {<br>    return InheritedModel.inheritFrom&lt;UserModel&gt;(context)!.user;<br>  }<br><br>  @override<br>  bool updateShouldNotify(UserModel oldWidget) {<br>    return user != oldWidget.user;<br>  }<br><br>  @override<br>  bool updateShouldNotifyDependent(<br>      UserModel oldWidget, Set&lt;User&gt; dependencies) {<br>    return user != oldWidget.user &amp;&amp; dependencies.contains(user);<br>  }<br>}</pre><ul><li>InheritedModel has the static of and updateShouldNotify same as InheritedNotifier. The static of method takes BuildContext and uses the inheritFrom method provided by InheritedModel to retrieve the UserModel and access its user variable.</li><li>updateShouldNotifyDependent method is used to determine whether specific dependent widgets should be notified and rebuilt when the InheritedModel is rebuilt.</li><li>It takes two parameters: oldWidget which represents the previous instance of the model, and dependencies, which is a set of aspects that the widget depend on. Here, we can read the aspect value of the dependent widgets and can specify the condition on which we want our dependent widgets to be rebuilt.</li></ul><h4>Using the InheritedModel</h4><p>Let’s use the InheritedModel in the UI.</p><pre>class HomePage extends StatefulWidget {<br>  const HomePage({super.key});<br><br>  @override<br>  State&lt;HomePage&gt; createState() =&gt; _HomePageState();<br>}<br><br>class _HomePageState extends State&lt;HomePage&gt; {<br>  final TextEditingController _nameController = TextEditingController();<br>  final TextEditingController _ageController = TextEditingController();<br><br>  User user = User();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;InheritedNotifier Demo&#39;),<br>      ),<br>      body: Center(<br>        child: UserModel(<br>          user: user,<br>          child: Builder(builder: (context) {<br>            return Column(<br>              crossAxisAlignment: CrossAxisAlignment.start,<br>              mainAxisAlignment: MainAxisAlignment.center,<br>              children: [<br>                Text(<br>                  &#39;Name : ${UserModel.of(context)!.name}&#39;,<br>                  style: const TextStyle(fontSize: 20),<br>                ),<br>                Text(<br>                  &#39;Age : ${UserModel.of(context)!.age}&#39;,<br>                  style: const TextStyle(fontSize: 20),<br>                )<br>              ],<br>            );<br>          }),<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton.extended(<br>          onPressed: () {<br>            showModalBottomSheet(<br>                context: context,<br>                builder: (_) {<br>                  return Column(<br>                    children: [<br>                      TextField(<br>                        controller: _nameController,<br>                        decoration: const InputDecoration(<br>                            hintText: &#39;What is your name?&#39;,<br>                            border: OutlineInputBorder()),<br>                      ),<br>                      const SizedBox(<br>                        height: 20,<br>                      ),<br>                      TextField(<br>                        controller: _ageController,<br>                        decoration: const InputDecoration(<br>                          hintText: &#39;What is your age?&#39;,<br>                          border: OutlineInputBorder(),<br>                        ),<br>                        keyboardType: TextInputType.number,<br>                      ),<br>                      ElevatedButton(<br>                          onPressed: () {<br>                            User updatedUSer = User(<br>                                name: _nameController.text,<br>                                age: _ageController.text);<br>                            Navigator.pop(context);<br>                            setState(() {<br>                              user = updatedUSer;<br>                            });<br>                          },<br>                          child: const Text(&quot;Save&quot;))<br>                    ],<br>                  );<br>                });<br>          },<br>          label: const Text(&#39;Set Profile&#39;)),<br>    );<br>  }<br>}</pre><p>Pretty similar, isn’t it?</p><p>And just like that, your app is ready. Hit that Run button and update your information to see the result.</p><p>How does it work?</p><p>When you click on the button, the value of the <em>user</em> variable changes. As this change happens, our UserModel observes the change and its <strong>updateShouldNotify </strong>method is called. This method checks if the dependent widgets need to be rebuilt. If this method returns true, which it would if any one of the properties changes, then <strong>updateShouldNotifyDependent </strong>is called.</p><h4>Key Points</h4><ul><li>By specifying aspects, InheritedModel reduces the number of widget rebuilds that occur when changes are made to shared data. This optimization improves performance by only updating the widget that depends on specific changes.</li><li>InheriteModel allows you to manage multiple models and control specific aspects that each dependent widget relies on.</li><li>Compared to InheritedWidget, using InheritedModel requires more explicit specifications of dependencies and aspects, which can increase the complexity of the code.</li><li>You can use it when you have multiple models or shared data with different aspects that need to be managed separately and When you want to optimize performance by reducing unnecessary rebuilds of widgets that don’t depend on specific changes in the shared data.</li></ul><h3>Conclusion</h3><p>This is the most basic example I could come up with. In this article, we have explored InheritedNotifier and InheritedModel as subclasses of InheritedWidget in Flutter.</p><p>I hope this article has given you enough information to explore and utilize InheritedWidget in your Flutter projects, particularly for smaller projects with simpler use cases. If you have any questions or feedback, feel free to leave them in the comments section. I encourage you to try these classes and experiment with them in your own projects.</p><p>Thanks for reading!! 👋 👋</p><h3>Useful Related Articles</h3><ul><li><a href="https://blog.canopas.com/flutter-customizing-serialization-and-deserialization-with-json-serializable-db17e3aa90b0">Flutter — Customizing Serialization and Deserialization with json_serializable</a></li><li><a href="https://blog.canopas.com/optimizing-flutter-apps-mastering-flutter-inspector-devtools-for-effective-debugging-493c03f68835">Optimizing Flutter Apps: Mastering Flutter Inspector DevTools for Effective Debugging</a></li><li><a href="https://blog.canopas.com/how-to-maintain-the-state-of-bottomnavigationbar-across-tabs-528b3699f78b">How to Maintain the state of BottomNavigationBar across tabs</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedbacks and suggestions are most welcome, add them in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fd64ce52b66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/how-to-use-inheritedwidget-in-flutter-5fd64ce52b66">How to Use InheritedWidget in Flutter</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Flutter Apps: Mastering Flutter Inspector DevTools for Effective Debugging]]></title>
            <link>https://medium.com/canopas/optimizing-flutter-apps-mastering-flutter-inspector-devtools-for-effective-debugging-493c03f68835?source=rss-f50ffffc2644------2</link>
            <guid isPermaLink="false">https://medium.com/p/493c03f68835</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[devtools]]></category>
            <dc:creator><![CDATA[Sneha S]]></dc:creator>
            <pubDate>Thu, 18 May 2023 10:25:40 GMT</pubDate>
            <atom:updated>2023-05-18T10:25:40.662Z</atom:updated>
            <content:encoded><![CDATA[<h4>Utilize Flutter Inspector DevTools to debug the performance of a Flutter app</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9XkzX5bpeVOuycoZ-FWbg.png" /><figcaption>Designed By <a href="https://canopas.com/">Canopas</a></figcaption></figure><p>As a Flutter developer, You’ve come across those frustrating UI-related issues that make your app display a bothersome yellow and black striped line on the screen. In fact, two of the most frequently encountered errors are directly related to <strong>Widget Overflow,</strong> and <strong>Vertical viewport was given unbounded height</strong>. but, With <strong>Flutter Inspector,</strong> we can solve these errors and optimize Flutter app performance.</p><p>In this article, we’ll explore how to use <strong>Flutter Inspector</strong> to debug and optimize performance, including a step-by-step demonstration on a sample screen.</p><h3>Table of Contents</h3><pre><strong>· </strong><a href="#0588"><strong>Introduction</strong></a><strong><br>· </strong><a href="#b0f9"><strong>What is Flutter Inspector?</strong></a><strong><br></strong>  - <a href="#361c">Widget Tree</a><br>  - <a href="#b343">Layout Explorer</a><br>  - <a href="#a757">Widget Detail pane</a><br><strong>· </strong><a href="#b243"><strong>Toolbar</strong></a><strong><br></strong>  - <a href="#d45c">Select widget mode</a><br>  - <a href="#7cbf">Refresh Tree</a><br>  - <a href="#e599">Slow Animations</a><br>  - <a href="#c063">Show Guidelines Mode</a><br>  - <a href="#aed9">Show Baselines</a><br>  - <a href="#2923">Highlight repaints</a><br>  - <a href="#95dc">Highlight Oversized Images</a><br><strong>· </strong><a href="#1685"><strong>Get Started</strong></a><strong><br></strong>  - <a href="#544e">Header</a><br>    · <a href="#ae7c">Fixing Overflow Error</a><br>  - <a href="#a972">Main Section</a> <br>    · <a href="#ceb6">Fixing Unbounded Height Error</a><br>  - <a href="#68c1">Footer</a><br>  - <a href="#612c">Fixing Highlight Image</a><br><strong>· </strong><a href="#7672"><strong>Conclusion</strong></a></pre><h3>Sponsored</h3><p>Positive thinking leads to positive outcomes. Try out <a href="https://justly.life/dl"><strong>Justly</strong></a><strong>, </strong>build good habits, and start thinking positively today!</p><p><a href="https://justly.life/download">Justly: Habits, Goals, Journal</a></p><h3>Introduction</h3><p>The<strong> Flutter Inspector DevTools</strong> allows you to explore the widget tree visually and provides a graphical interface that allows you to dive deep into the structure and behavior of the Flutter app. The Flutter Inspector can assist in debugging layout-related issues. By utilizing the inspector’s visual widget tree, we can inspect the properties of individual widgets and identify misconfiguration in widget properties.</p><p>Before we dive into our debugging adventure, let’s first familiarize ourselves with that <strong>Flutter Inspector</strong> and the valuable tools it provides.</p><blockquote>To debug a layout issue, run the app in <a href="https://docs.flutter.dev/testing/build-modes#debug">debug mode</a> and open the inspector by clicking the <strong>Flutter Inspector</strong> tab on the DevTools toolbar.</blockquote><h3>What is Flutter Inspector?</h3><p>Let’s explore the key components of Flutter Inspector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*7xPWNCzWE30xN-BDGelhzA.png" /></figure><h4>Widget Tree</h4><p>The <strong>Widget Tree </strong>provides a visual representation of the widget hierarchy of the app’s UI. The widget tree allows you to navigate through the different widgets, inspect their properties, and identify their relationship.</p><h4>Layout Explorer</h4><p>The <strong>Layout Explorer</strong> in <strong>Flutter Inspector</strong> focuses on analyzing both flex layout and fixed-size layout</p><p>For <strong>Flex layouts</strong>, such as Row, Column, and Flex, the <strong>Layout Explorer</strong> visualizes the layout of flex widgets and their children. It identifies the main and cross axes, alignment, flex, and layout constraints. It also highlights overflow errors, helping developers understand and resolve these issues.</p><p>By clicking on a widget in the <strong>Layout Explorer</strong>, you can mirror the selection on the on-device inspector, allowing for inspection and modification of widget properties. You can make changes to properties like flex factor, flex fit, and alignment directly in the Explorer, with real-time updates reflected on the device. These modifications are temporary and do not affect the source code.</p><p>For <strong>Fixed-size </strong>layouts, the<strong> Layout Explorer</strong> provides size, constraint, and padding information for selected widgets. This data gives you information on how these widgets are positioned and spaced within the layout.</p><h4>Widget Detail Pane</h4><p>The <strong>Widget Detail Pane</strong> displays the properties and values of the selected widget in the widget tree. It provides detailed information about the widget, including types, constraints, padding, margin, and more.</p><h3>Toolbar</h3><p>The following tools are available in the Flutter inspector’s toolbar:</p><h4><strong>Select widget mode</strong></h4><p>By enabling this mode, you can select widgets on the device and inspect their properties. This allows you to dive deep into the specific details of the widget and understand its behavior within the UI.</p><h4>Refresh Tree</h4><p>Use this option to reload and update the widget information in the Inspector. If you’ve made changes to your app’s UI and want the Inspector to reflect those changes, simply click on the Refresh button. It ensures that you’re working with the most up-to-date widget tree information.</p><h4>Slow Animations</h4><p>This feature slows down animations 5 times. It’s particularly useful when you want to ensure smooth and visually appealing animations in your app. By enabling Slow Animations, you can observe the animation frame by frame and make any necessary adjustments to achieve the desired visual effect.</p><h4>Show Guidelines Mode</h4><p>Enabling this mode overlays guidelines on the screen to assist you in fixing layout issues. These guidelines act as visual references, helping you align and position widgets accurately within your UI.</p><h4>Show Baselines</h4><p>This option displays baselines, which are essential for aligning text correctly. Selecting this option will make all the baselines visible, allowing you to check the alignment of the text precisely.</p><h4>Highlight Repaints</h4><p>Enabling this feature shows borders around elements that repaint when their state changes. It helps identify unnecessary repaints and optimize your app’s rendering performance.</p><h4>Highlight Oversized Images</h4><p>This tool highlights images that consume excessive memory by inverting their colors. It allows you to easily identify and optimize image resources, ensuring efficient memory usage in your app. By optimizing image sizes or using compressed formats, you can reduce memory usage and enhance app performance.</p><p>Great features, isn’t it?…</p><p>Let’s dive into how we can use these tools to implement our Demo screen and fix any layout issues that come our way.</p><h3>Get Started</h3><p>Let’s incorporate the case study into this article. We’ll build the below screen using Flutter Inspector for debugging purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Ijc9r0z-0nVTP7iotOdtkQ.png" /></figure><p>This is our main.dart file</p><pre>void main() {<br>  runApp(const MaterialApp(home: MyApp()));<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Buy Medicine&#39;),<br>        centerTitle: true,<br>      ),<br>      body: Padding(<br>        padding: const EdgeInsets.all(15),<br>        child: Column(<br>          children: [<br>            // Sections of the screen will be placed here<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>We can start by implementing the three sections of our screen: The Header with User information, the Main Section with ListView, and the Footer with a button.</p><h3>Header</h3><p>Let’s add a Header that displays User information. We’ll create UserInformation Widget for that. Here’s the code:</p><pre>class UserInformation extends StatelessWidget {<br>  const UserInformation({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return  Row(<br>      children: [<br>        Column(<br>          crossAxisAlignment: CrossAxisAlignment.start,<br>          children: const [<br>            Text(&#39;Hi Ninja, 👋🏻  &#39;,<br>                style: TextStyle(<br>                    fontSize: 20, fontWeight: FontWeight.bold)),<br>            SizedBox(height: 10,),<br>            Text(<br>              &#39;Relieve Your Cough with our top Recommended Medicines&#39;,style: TextStyle(fontSize: 17),)<br>          ],<br>        ),<br>        const CircleAvatar(<br>            minRadius: 30,<br>            backgroundImage: NetworkImage(<br>                &#39;https://img.freepik.com/premium-vector/woman-profile-cartoon_18591-58477.jpg&#39;)),<br>      ],<br>    );<br>  }<br>}</pre><p>When you run the app, you’ll see an overflow error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*FyDJRoG9bA6LI-JLScyy-g.png" /></figure><h4>Fixing Overflow error</h4><p>Don’t panic! Let’s follow the debugging steps to identify and fix the issue.<br>1. In Terminal, You’ll see errors like this</p><pre>======== Exception caught by rendering library =====================================================<br>The following assertion was thrown during layout:<br>A RenderFlex overflowed by 128 pixels on the right.<br><br>The relevant error-causing widget was: <br>  Row Row ...<br>The overflowing RenderFlex has an orientation of Axis.horizontal.<br>The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and black striped pattern. This is usually caused by the contents being too big for the RenderFlex.<br><br>Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the RenderFlex to fit within the available space instead of being sized to their natural size.<br>This is considered an error condition because it indicates that there is content that cannot be seen. If the content is legitimately bigger than the available space, consider clipping it with a ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex, like a ListView.<br><br>◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤</pre><p>2. Navigate to <strong>DevTools</strong> and open the <strong>Layout Explorer</strong> tab</p><p>Click on Errors and you’ll see that a Red banner appears at the bottom indicating that something is wrong. Let’s take a closer look at it, We observe that the width of a Text widget is 468, while the parent’s width is 400. Additionally, the children’s width sum up to 528, resulting in a RenderFlex overflowed by 120 pixels on the Right.</p><p>Let’s set the flex factor of the Column widget to 1, it’s like wrapping the widget in Expanded widget, as the default value of flex is 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Xl-MDTtS_3rBlkJRxDKXtw.gif" /></figure><p>Great 👍. The issue is fixed…or is it?.</p><p>Unfortunately, when you run the app again, the issue comes back. Why?</p><p>As we saw earlier, These modifications are temporary and don’t affect the source code. So, let’s wrap the Column widget in the Expanded widget to ensure that it takes only the necessary space within the raw.</p><pre>class UserInformation extends StatelessWidget {<br>  const UserInformation({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return  Row(<br>      children: [<br>        Expanded(<br>          child: Column(<br>     ....<br>        ),<br>     .... <br>}</pre><p>And there you have it!!</p><p>Now, let’s move on to the Main section of our screen.</p><h3>Main Section</h3><pre>class MedicineList extends StatelessWidget {<br>  const MedicineList({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return  ListView(<br>      children: [<br>        ListTile(...),<br>        ListTile(...),<br>        ListTile(...),<br>      ],<br>    );<br>  }<br>}</pre><p>We have the MedicineList widget which is a Simple ListView containing ListTile widgets to display basic information about medicines.</p><p>Let’s add MedicineList Widget to our MyApp class in our main.dart file</p><pre>class MyApp extends StatelessWidget {<br>....<br>  @override<br>  Widget build(BuildContext context) {<br>    ....<br>        child: Column(<br>          children:const  [<br>            UserInformation(),<br>            MedicineList()<br>          ],<br>        ),<br>}</pre><p>Now, if you run the app, you may encounter an issue where nothing is displayed on the screen and you’ll see the following error.</p><pre>======== Exception caught by rendering library =====================================================<br>The following assertion was thrown during performResize():<br>Vertical viewport was given unbounded height.<br><br>Viewports expand in the scrolling direction to fill their container. In this case, a vertical viewport was given an unlimited amount of vertical space in which to expand. This situation typically happens when a scrollable widget is nested inside another scrollable widget.<br><br>If this widget is always nested in a scrollable widget there is no need to use a viewport because there will always be enough vertical space for the children. In this case, consider using a Column or Wrap instead. Otherwise, consider using a CustomScrollView to concatenate arbitrary slivers into a single scrollable.<br><br>The relevant error-causing widget was: <br>  ListView ListView ....</pre><h4>Fixing Unbounded Height Error</h4><p>Open up the <strong>Flutter inspector</strong> and click on the MedicineList widget.</p><p>Nothing appears in the<strong> Layout Explorer</strong> after clicking on the MedicineList. That’s because <strong>Layout Explorer</strong> only supports Flex widgets and their direct children.</p><p>So, let’s move on to the next step and open the <strong>Widget Details Tree</strong> and expand renderObject in Listview.</p><p>You’ll notice that the Size parameter is missing and highlighted in Orange color. Additionally, the constraints are shown as <strong>BoxConstraints(0.0≤w≤400,0.0≤h≤infinity)</strong>, indicating that height is infinite in its scrolling direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Wbv6Q8rgUTKBZi_1hb3PNw.png" /></figure><p>So, 🤔 what’s happening here?</p><blockquote><strong>Constraints go down. Sizes go up, and Parent sets position.</strong></blockquote><p>In Flutter, Each<strong> </strong>widget gets its own constraints from its parent and asks each child what size it wants to be and the child widget tells its parent about size. However, in our case, as the parent, the Column widget did not provide any height and ListView is taking infinite height. As a result, the widgets don’t know how to handle the situations.<br>To resolve this, Let’s wrap Listview in the Expanded widget as it gives bounded constraints along the parent’s main axis, which will provide the ListView with a proper height.</p><pre>class MedicineList extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return  Expanded(<br>       child: ListView(<br>        ...<br>      ),<br>    );<br>  }<br>}</pre><p>Now, hot reload the app and see the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*PGFHqIjMaGpslU-0s2orKw.png" /></figure><h3>Footer</h3><pre>class CartButton extends StatelessWidget {<br>  const CartButton({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SizedBox(<br>      height: 50,<br>      width: 200,<br>      child: ElevatedButton(<br>        onPressed: () {},<br>        child: Row(<br>          children: const [<br>            Icon(Icons.shopping_cart),<br>            SizedBox(<br>              width: 20,<br>            ),<br>            Text(<br>              &#39;Add To Cart&#39;,<br>              style: TextStyle(fontSize: 20),<br>            )<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Let’s add CartButton to MyApp class in main.dart file.</p><pre>class MyApp extends StatelessWidget {<br> @override<br>  Widget build(BuildContext context) {<br>    .... <br>        child: Column(<br>          children:const  [<br>            UserInformation(),<br>            MedicineList(),<br>            CartButton()<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>So, now let’s run the app, you’ll see the below output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*uWzeYZhwlC2hlriHeEDg3w.png" /></figure><p>We are done, right? Hold on, we are missing that horizontal line between UserInformation and Listview So, let’s add Divider.</p><pre>Column(<br>  children:const  [<br>    UserInformation(),<br>    Divider(),<br>    MedicineList(),<br>    CartButton()<br>  ],<br>),</pre><p>Hot reload. complete!! 😃</p><p>But wait, a question might pop up in your mind: what’s the purpose of tools in the toolbar of Flutter Inspector? As we used a NetworkImage in our implementation, let’s enable the <strong>Highlight Image</strong> tool and see what happens.</p><h4>Fixing Highlight Image</h4><p>Open <strong>Flutter Inspector</strong> and enable the <strong>Highlight Image</strong> option and you got the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Nj6MLCUum5hMWrb3lSvdKA.png" /></figure><p>But, What’s that? Check the error message in the console.</p><pre>======== Exception caught by painting library ======================================================<br>The following message was thrown while painting an image:<br>Image https://img.freepik.com/premium-vector/woman-profile-cartoon_18591-58477.jpg has a display size of 210×210 but a decode size of 626×626, which uses an additional 1811KB.<br>Consider resizing the asset ahead of time, supplying a cacheWidth parameter of 210, a cacheHeight parameter of 210, or using a ResizeImage.</pre><p>We got this for Image in Header as we have used NetworkImage whose actual decoded size is 625*625 pixels and we provided a display size of 210*210 pixels. This means that Image is being loaded at a higher resolution than necessary, leading to increased memory usage.</p><p>Let’s use ResizeImage widget for memory optimization.</p><pre>class UserInformation extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    ....<br>         CircleAvatar(<br>            minRadius: 30,<br>            backgroundImage:ResizeImage(<br>              NetworkImage(),<br>              width: 210,<br>              height: 210<br>            ),<br>         )<br>      ],<br>    );<br>  }<br>}</pre><p>Here, we specify the desired display size of 210*210 pixels. By doing so, we’re telling Flutter to load the image at the right resolution, preventing unnecessary Memory consumption.</p><p>Now, let’s run the app once more.</p><p>No more error messages, just a smooth and Optimized UI 👍.</p><h3>Conclusion</h3><p>In this article, we have explored the power of the Flutter Inspector in debugging Flutter apps and resolving UI-related issues.</p><p>By utilizing the Widget tree, Layout explorer, and widget detail pane, we can visually navigate through the widget hierarchy, inspect properties and identify any misconfiguration or layout-related issues. The flutter inspector’s Performance optimization features, such as highlighting repaints and oversized images, help identify and resolve rendering and memory usage problems, ensuring a smooth and efficient app experience.</p><p>We hope this article has provided you with sufficient information on how to utilize the <strong>Flutter Inspector</strong> to recognize and resolve layout-related issues in your Flutter application. If you have any questions or comments, please don’t hesitate to leave them below.</p><p>Happy debugging! 👋</p><h3>Useful Articles</h3><ul><li><a href="https://blog.canopas.com/flutter-customizing-serialization-and-deserialization-with-json-serializable-db17e3aa90b0">Flutter — Customizing Serialization and Deserialization with json_serializable</a></li><li><a href="https://blog.canopas.com/how-to-maintain-the-state-of-bottomnavigationbar-across-tabs-528b3699f78b">How to Maintain the state of BottomNavigationBar across tabs</a></li></ul><h3>Thanks for the love you’re showing!</h3><p>If <strong>you </strong>like what you read, be sure you won’t miss a chance to give 👏 👏👏 below — as a writer it means the <strong>world</strong>!</p><p>Feedbacks and suggestions are most welcome, add them in the comments section.</p><p>Follow <a href="https://blog.canopas.com/"><strong>Canopas</strong></a><strong> </strong>to get updates on interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=493c03f68835" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopas/optimizing-flutter-apps-mastering-flutter-inspector-devtools-for-effective-debugging-493c03f68835">Optimizing Flutter Apps: Mastering Flutter Inspector DevTools for Effective Debugging</a> was originally published in <a href="https://medium.com/canopas">Canopas</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>