<?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 Abhijith K on Medium]]></title>
        <description><![CDATA[Stories by Abhijith K on Medium]]></description>
        <link>https://medium.com/@abhijithkonnayil?source=rss-4c427139bef9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OtnU5yLOupnnIvmkQFw8oA.jpeg</url>
            <title>Stories by Abhijith K on Medium</title>
            <link>https://medium.com/@abhijithkonnayil?source=rss-4c427139bef9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:44:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhijithkonnayil/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[CI/CD with Fastlane and GitHub Actions for Flutter (Android) | Part 1]]></title>
            <link>https://abhijithkonnayil.medium.com/ci-cd-with-fastlane-and-github-actions-for-flutter-android-part-1-03dbc851ee8d?source=rss-4c427139bef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/03dbc851ee8d</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[fastlane]]></category>
            <dc:creator><![CDATA[Abhijith K]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 18:36:35 GMT</pubDate>
            <atom:updated>2025-06-01T18:36:35.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Streamlining Flutter Android deployment with Fastlane and GitHub Actions in a robust CI/CD pipeline." src="https://cdn-images-1.medium.com/max/1024/1*q_TGc2LMd0rTfhits2HTag.jpeg" /><figcaption>Streamlining Flutter Android deployment with Fastlane and GitHub Actions in a robust CI/CD pipeline.</figcaption></figure><h3>Prerequisites</h3><p>Fastlane is built in Ruby, so it’s helpful to have a basic understanding of Ruby. You can refer to the code snippets shared in this document.<br> You should also have a basic understanding of building and releasing Flutter apps. Additionally, <strong>you need a Flutter app with Firebase App Distribution enabled</strong>.</p><h3>What is Fastlane ?</h3><p>According to the official documentation:</p><blockquote>fastlane is an open source platform aimed at simplifying Android and iOS deployment. fastlane lets you automate every aspect of your development and release workflow.</blockquote><p>Fastlane helps us automate tasks related to deployment, such as code signing, testing, building, and releasing apps for both Android and iOS.</p><p>For example, let’s say you’re working on a Flutter project and it’s time to release a beta version to Firebase for testing. Here’s what you’d typically do:</p><ul><li>Run flutter test to make sure nothing is broken.</li><li>Update the build number.</li><li>Generate the build.</li><li>Publish it to Firebase App Distribution.</li></ul><p>You’d need to repeat these steps every time you want to publish a new build — which can be time-consuming. Fastlane lets you automate this whole process. You set it up once, and then you can do all of it with a single command! TADA</p><h3>What is Github Action?</h3><p>According to the official documentation:</p><blockquote>GitHub Actions is a continuous integration and continuous delivery (CI/CD) platform that allows you to automate your build, test, and deployment pipeline.</blockquote><p>GitHub Actions provides a platform to run commands for building, testing, and deploying your apps — so you don’t have to manually trigger these commands on your local machine.</p><p>You can write a config file to set up the environment and dependencies, define the tasks to be executed, and specify when the action should be triggered — whether manually, when a pull request is raised, or when a PR is merged.</p><h3>Setting up Fastlane in a Flutter Project</h3><p>For this, you should already have a Flutter project ready. We’re going to initialize Fastlane inside the project. (Refer to <a href="https://docs.fastlane.tools/getting-started/android/setup/">Fastlane’s official setup guide for Android</a> for more details.)</p><p>First, make sure Ruby is installed on your machine, and verify that the Ruby version is 2.5 or newer:</p><pre>ruby --version</pre><p>Next, we can install Fastlane directly into Ruby’s system environment, but this is <strong>not recommended</strong>. The preferred way is to install Fastlane using <strong>Bundler</strong>.</p><h4>1.<strong>Install Bundler</strong></h4><pre>gem install bundler</pre><h4>2.Create a Gemfile</h4><p>Create a Gemfile inside the android directory of your Flutter project and paste the following content:</p><pre>source &quot;https://rubygems.org&quot;<br><br>gem &quot;fastlane&quot;</pre><p>This specifies the required dependency( here fastlane) for Bundler, including the exact version if needed.</p><p>Now run bundle update, and then add both the Gemfile and Gemfile.lock to your version control.</p><pre>bundle update</pre><h4>3.Initilize Fastlane inside android directory</h4><pre>bundle exec fastlane init</pre><p>When prompted, enter the package name and skip the rest for now. This will create a fastlane directory inside the android folder, containing an Appfile (global config for the app) and a Fastfile (where custom lanes are defined).</p><figure><img alt="output for build exec fastlane init — 1" src="https://cdn-images-1.medium.com/max/1024/1*boeoiQ9psRBp2sGM1boOBQ.png" /><figcaption>output for build exec fastlane init — 1</figcaption></figure><figure><img alt="output for build exec fastlane init — 1" src="https://cdn-images-1.medium.com/max/1024/1*zForW-jNSna-v_8UKOQIVw.png" /><figcaption>output for build exec fastlane init — 2</figcaption></figure><h3><strong>Setting Up Fastlane Lanes</strong></h3><p>Let’s create a dummy lane to check if Fastlane is working correctly. Clear the contents of the Fastfile and add a simple hello lane</p><pre>default_platform(:android)<br><br>platform :android do<br>  desc &quot;Dummy lane to test fastlane setup&quot;<br>  lane :hello do<br>    sh(&quot;echo &#39;Hello ...&#39;&quot;)<br>  end<br>end #end platform :android</pre><p>This will simply print “Hello …” in console using echo command</p><p>Then run the following command inside the android directory:</p><pre>fastlane hello</pre><figure><img alt="output for `fastlane hello` lane" src="https://cdn-images-1.medium.com/max/1024/1*_iAP9ACNK4vqori3gdYTqA.png" /><figcaption>output for `fastlane hello` lane</figcaption></figure><p>The output showing the successful execution of the lane will be displayed. If you see that, you’re good to go!</p><p>Let’s briefly outline what we’ll implement in Fastlane for a simple build automation:</p><ol><li>get the latest build number from Firebase App Distribution</li><li>increment and update the build number in pubspec.yaml</li><li>generate the Flutter APK</li><li>upload the APK to Firebase App Distribution !!</li></ol><p>And that’s it — done!</p><h4>Fastlane Plugins</h4><p>To make these tasks easier, we will use the following Fastlane plugins:</p><ol><li>firebase_app_distribution : to get latest release and distribute the APK</li><li>flutter_versioner : to update pubspec.yaml</li></ol><p>To authenticate with Firebase, you need Google Service Account credentials. You can generate these by following the steps here:<br> <a href="https://firebase.google.com/docs/app-distribution/ios/distribute-fastlane#service-acc-fastlane">Firebase App Distribution with Fastlane — Service Account Setup</a></p><p>This will give you a JSON file that looks like this:</p><pre>{<br>  &quot;type&quot;: &quot;service_account&quot;,<br>  &quot;project_id&quot;: &quot;project-id&quot;,<br>  &quot;private_key_id&quot;: &quot;773....3&quot;,<br>  &quot;private_key&quot;: &quot;-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n&quot;,<br>  &quot;client_email&quot;: &quot;firebase...gserviceaccount.com&quot;,<br>  &quot;client_id&quot;: &quot;1...2&quot;,<br>  &quot;auth_uri&quot;: &quot;https://accounts.google.com/o/oauth2/auth&quot;,<br>  &quot;token_uri&quot;: &quot;https://oauth2.googleapis.com/token&quot;,<br>  &quot;auth_provider_x509_cert_url&quot;: &quot;https://www.googleapis.com/oauth2/v1/certs&quot;,<br>  &quot;client_x509_cert_url&quot;: &quot;https://www.googleapis.com/....gserviceaccount.com&quot;,<br>  &quot;universe_domain&quot;: &quot;googleapis.com&quot;<br>}</pre><p>To authenticate requests locally, you need to set the path to this JSON file in the environment variable GOOGLE_APPLICATION_CREDENTIALS.</p><pre> export GOOGLE_APPLICATION_CREDENTIALS=/absolute/path/to/credentials/file.json</pre><h4>Installing Fastlane plugins</h4><p>Now, install the plugins we mentioned above.</p><pre> bundle exec fastlane add_plugin firebase_app_distribution flutter_versioner</pre><p>This will create a Pluginfile inside the fastlane folder. This auto generated file will contain the list of fastlane plugins we need</p><pre># Autogenerated by fastlane<br>#<br># Ensure this file is checked in to source control!<br><br>gem &#39;fastlane-plugin-firebase_app_distribution&#39;<br>gem &#39;fastlane-plugin-flutter_versioner&#39;</pre><h4>Setting up .env for secrets</h4><p>Create a .env file inside the android/fastlane directory to store your secrets, including the app ID. Make sure this file is <strong>not</strong> committed to Git.</p><pre>APP_ID=1:3--5:android:a--2</pre><h4>Building the `update_build_number` lane</h4><p>For every build released to Firebase App Distribution, we need a unique build number. To achieve this, we increment the build number by 1 for each subsequent release. For simplicity, here we focus only on updating the build number.</p><p>The firebase_app_distribution_get_latest_release plugin fetches the latest release from which we can get the build number . Then we increment the build number by 1. If no release exists yet, we start the build number at 1.</p><p>The flutter_versioner plugin updates the build number (version_code) in pubspec.yaml.</p><p>Pass your app ID from the .env file as a parameter to firebase_app_distribution_get_latest_release.</p><p>firebase_app_distribution_get_latest_release. To update the build number, provide version_component as version_code and pass the new build number as the value to flutter_versioner. This updates the build number in pubspec.yaml.</p><p>You can also update other version-related components using flutter_versioner, such as the version name, version code, or even the major, minor, or patch parts of the version name.</p><pre>platform :android do<br>...<br>desc &quot;lane to update build number&quot;<br>  lane :update_build_number do<br><br>    # get the latest release from Firebase App Distribution<br>    latest_release = firebase_app_distribution_get_latest_release(<br>    app: ENV[&#39;APP_ID&#39;],)<br>    <br>    # if no releases found, set build_number to 1, otherwise increment the latest release version<br>    build_number = 1<br>    if(latest_release.nil?)<br>      puts &quot;No releases found.&quot;<br>    else<br>      build_number =  latest_release[:buildVersion].to_i + 1<br>    end<br>    #sets the build number in pubspec.yaml<br>    flutter_versioner(<br>      version_component:&quot;version_code&quot;,<br>      value:&quot;#{build_number}&quot;<br>      )<br>  end<br>....<br>end #end platform :android</pre><p>Test the lane if ,it executes successfully</p><pre> bundle exec fastlane update_build_number</pre><h4>Building the `build_apk` lane</h4><p>This lane builds the Flutter APK using the standard Flutter command. Before running the command, we change the directory to the Flutter root since the current directory is android.</p><pre>platform :android do<br>...<br>lane :build_apk do<br>    Dir.chdir &#39;../..&#39; do<br>      sh(&quot;flutter&quot;,&quot;build&quot;,&quot;apk&quot;,)<br>    end<br>  end<br>...<br>end #end platform :android</pre><p>Test the lane and check, if it generates the build</p><pre>bundle exec fastlane build   </pre><h4>Building the `distribute` lane</h4><p>This lane use firebase_app_distribution to uploads the APK to Firebase App Distribution. Pass the app ID from the .env file along with the APK path. Since we’re not using flavors or a custom location, the APK can be found in the default build location.</p><pre>platform :android do<br>...<br>lane :distribute do<br>  firebase_app_distribution(<br>    app: ENV[&#39;APP_ID&#39;],<br>    apk_path: &quot;../build/app/outputs/flutter-apk/app-release.apk&quot;,<br>    )  <br>  end<br>...<br>end #end platform :android</pre><p>Test the lane and verify if the build generated in the previous step is successfully uploaded to Firebase App Distribution.</p><pre>bundle exec fastlane distribute</pre><h3>Configuring GitHub Actions Workflow for Flutter</h3><p>GitHub Actions uses YAML files to define workflows. To set up our workflow, create a file named publish.yaml inside the .github/workflows directory.</p><p>A typical workflow file include<br>A typical workflow file includes:</p><ol><li><strong>name:</strong> The name of the workflow (we’ll use <strong>Build and Publish</strong>)</li><li><strong>on:</strong> The events that trigger the workflow (for simplicity, we’ll trigger it manually)</li><li><strong>jobs:</strong> One or more jobs that run on a GitHub runner</li></ol><p>Here’s an overview of the jobs we will perform:</p><ol><li>checkout to the repository code</li><li>setup flutter</li><li>install pub dependencies</li><li>setup ruby</li></ol><p>uses: runs predefined GitHub Actions or workflows, while run: executes custom shell commands within a job step.</p><pre>name: Build and Publish #name of the workflow<br>on:<br>  workflow_dispatch: # Allows manual triggering of the workflow<br><br>jobs: # Define the jobs<br>  build: # Build job <br>    runs-on: ubuntu-latest # The job will run on the latest Ubuntu environment<br>    steps:<br>      - name: Checkout code   # Checkout the repository code<br>        uses: actions/checkout@v2 <br>      <br>      - name: Setup Flutter # Setup Flutter environment<br>        uses: subosito/flutter-action@v1<br>        with:<br>          channel: &#39;stable&#39;<br>          flutter-version: 3.32.0<br><br>      - name: Install dependencies # Install Flutter dependencies<br>        run: flutter pub get<br><br>      - name: Set up Ruby    #Setup Ruby<br>        uses: ruby/setup-ruby@v1<br>        with:<br>          ruby-version: &#39;3.3&#39;</pre><h3>Export Environment variable for Github Action</h3><p>The Google service account credentials need to be available in the GitHub runner environment. However, for security reasons, you should never commit these credentials directly in your code. Instead, use GitHub Secrets.</p><h4>1.Add the Secrets in Github secrets.</h4><p>Setting &gt; Actions &gt; New repository secrets</p><ol><li>APP_ID : Your Firebase App ID</li><li>GOOGLE_SERVICE_ACCOUNT_ENCODED : Your Google service account JSON encoded in Base64</li></ol><p>The following command will encode the json to a text file named encoded.txt</p><pre> base64 service.json &gt; encoded.txt             </pre><p>The content of the encoded.txt file should be copied and added as the value for the secret GOOGLE_SERVICE_ACCOUNT_ENCODED.</p><figure><img alt="Adding GOOLE_SERVICE_ACCOUNT_ENCODED to GitHub secrets" src="https://cdn-images-1.medium.com/max/1024/1*NH_XArH3oDL3SIQ6u4c4MA.png" /><figcaption>Adding GOOLE_SERVICE_ACCOUNT_ENCODED to GitHub secrets</figcaption></figure><figure><img alt="Keys added in Github secrets" src="https://cdn-images-1.medium.com/max/795/1*KlO6X7xJjX8DMf1lM3LCAA.png" /><figcaption>Keys added in Github secrets</figcaption></figure><h4>2. Add Steps to export the Credentials to runner environment</h4><p>The “Create credentials file” step will decode the value stored in the GitHub secret and write it to a file. The next step will export the file path to the GOOGLE_APPLICATION_CREDENTIALS environment variable.</p><pre>- name: Create credentials file #decode and write the json content from secrets to service-account.json<br>  run: echo &quot;${{ secrets.GOOGLE_SERVICE_ACCOUNT_ENCODED }}&quot; | base64 -d &gt; ${{ github.workspace }}/service-account.json<br><br>- name: Set environment variable for Google credentials #export the file path to GOOGLE_APPLICATION_CREDENTIALS<br>  run: echo &quot;GOOGLE_APPLICATION_CREDENTIALS=${{ github.workspace }}/service-account.json&quot; &gt;&gt; $GITHUB_ENV</pre><h4>3.Export APP_ID to environment</h4><p>In this step well will export the APP_ID from secrets to Github environment</p><pre>- name: Set environment variable for APP_ID #export the APP_ID<br>  run: echo &quot;APP_ID=${{ secrets.APP_ID }}&quot; &gt;&gt; $GITHUB_ENV</pre><h3>Integrating Fastlane with GitHub Actions</h3><p>Now lets call the fastlane.</p><p>We will set up Fastlane and execute the lanes in the workflow steps.</p><h4>1. Install dependencies</h4><p>This step changes to the android directory and installs Fastlane along with other dependencies specified in the Gemfile.</p><pre>- name: Install dependencies<br>  run: |<br>    cd android <br>    bundle install</pre><h4>2. <strong>Execute the Fastlane lanes</strong></h4><p>These steps chages the directory to andorid and execute the 3 lanes we defined in the previously one by one.</p><ol><li>Update Build Number : updates the build number in pubspec.yaml</li><li>Generate APK : generates the apk with corresponding build number</li><li>Distribute APK: uploads the APK to firebase</li></ol><pre>- name: Update Build Number<br>  run: |<br>     cd android<br>     bundle exec fastlane update_build_number<br>     <br>- name: Generate APK<br>  run: |<br>     cd android<br>     bundle exec fastlane build_apk<br><br>- name: Distribute APK<br>  run: |<br>     cd android<br>     bundle exec fastlane distribute</pre><p>Done.</p><h3>Executing the workflow</h3><p>Push the code to github</p><p>Then, go to the <strong>Actions</strong> tab in your repository. On the left side, you will see your workflow named <strong>Build and Publish</strong> — select it.<br> On the right, click the <strong>Run workflow</strong> dropdown, then click the <strong>Run workflow</strong> button to start the process</p><figure><img alt="Triggering the workflow in Github" src="https://cdn-images-1.medium.com/max/1024/1*ebyyZw9HOBzrGzvT2QSYJw.png" /><figcaption>Triggering the workflow in Github</figcaption></figure><p>You will see the following screen upon successful execution.</p><figure><img alt="Completed workflow execution" src="https://cdn-images-1.medium.com/max/1024/1*i_piUD87cyhNLdfPJ2n0ig.png" /><figcaption>Completed workflow execution</figcaption></figure><p>You can view the uploaded APK in your Firebase App Distribution console.</p><figure><img alt="Build distributed in Firebase App Distribution" src="https://cdn-images-1.medium.com/max/751/1*zzmD11cMEU-Od_T9nVKAPw.png" /><figcaption>Build distributed in Firebase App Distribution</figcaption></figure><h3>The whole files</h3><p>Fastfile</p><pre>default_platform(:android)<br><br>platform :android do<br>  desc &quot;Dummy lane to test fastlane setup&quot;<br>  lane :hello do<br>    sh(&quot;echo &#39;Hello ...&#39;&quot;)<br>  end<br><br>  desc &quot;lane to update build number&quot;<br>  lane :update_build_number do<br><br>    # get the latest release from Firebase App Distribution<br>    latest_release = firebase_app_distribution_get_latest_release(<br>    app: ENV[&#39;APP_ID&#39;],)<br>    <br>    # if no releases found, set build_number to 1, otherwise increment the latest release version<br>    build_number = 1<br>    if(latest_release.nil?)<br>      puts &quot;No releases found.&quot;<br>    else<br>      build_number =  latest_release[:buildVersion].to_i + 1<br>    end<br><br>    flutter_versioner(<br>      version_component:&quot;version_code&quot;,<br>      value:&quot;#{build_number}&quot;<br>      )<br>  end<br><br>  lane :build_apk do<br>    Dir.chdir &#39;../..&#39; do<br>      sh(&quot;flutter&quot;,&quot;build&quot;,&quot;apk&quot;,)<br>    end<br>  end<br><br>  lane :distribute do<br>  firebase_app_distribution(<br>    app: ENV[&#39;APP_ID&#39;],<br>    apk_path: &quot;../build/app/outputs/flutter-apk/app-release.apk&quot;,<br>    )  <br>  end<br><br><br>end #end platform :android</pre><p>publish.yaml</p><pre>name: Build and Publish #name of the workflow<br>on:<br>  workflow_dispatch: # Allows manual triggering of the workflow<br><br>jobs: # Define the jobs<br>  build: # Build job <br>    runs-on: ubuntu-latest # The job will run on the latest Ubuntu environment<br>    steps:<br>      - name: Checkout code   # Checkout the repository code<br>        uses: actions/checkout@v2 <br>      <br>      - name: Setup Flutter # Setup Flutter environment<br>        uses: subosito/flutter-action@v1<br>        with:<br>          channel: &#39;stable&#39;<br>          flutter-version: 3.32.0<br><br>      - name: Install dependencies # Install Flutter dependencies<br>        run: flutter pub get<br><br>      - name: Set up Ruby    #Setup Ruby<br>        uses: ruby/setup-ruby@v1<br>        with:<br>          ruby-version: &#39;3.3&#39;<br>      <br>      - name: Create credentials file #decode and write the json content from secrets to service-account.json<br>        run: echo &quot;${{ secrets.GOOGLE_SERVICE_ACCOUNT_ENCODED }}&quot; | base64 -d &gt; ${{ github.workspace }}/service-account.json<br><br>      - name: Set environment variable for Google credentials #export the file path to GOOGLE_APPLICATION_CREDENTIALS<br>        run: echo &quot;GOOGLE_APPLICATION_CREDENTIALS=${{ github.workspace }}/service-account.json&quot; &gt;&gt; $GITHUB_ENV<br>      <br>      - name: Set environment variable for APP_ID #export the APP_ID<br>        run: echo &quot;APP_ID=${{ secrets.APP_ID }}&quot; &gt;&gt; $GITHUB_ENV<br>      <br>      - name: Install dependencies<br>        run: |<br>          cd android <br>          bundle install<br><br>      - name: Update Build Number<br>        run: |<br>          cd android<br>          bundle exec fastlane update_build_number<br>      <br>      - name: Generate APK<br>        run: |<br>          cd android<br>          bundle exec fastlane build_apk<br><br>      - name: Distribute APK<br>        run: |<br>          cd android<br>          bundle exec fastlane distribute</pre><h3>Troubleshooting Common Issues</h3><ol><li>Handling the YAML workflow file requires careful attention to formatting — <strong>even a single space or indentation mistake can cause the entire workflow to fail.</strong></li><li>When encoding your Google Service Account JSON file to base64 for use as a GitHub secret, <strong>missing or extra characters — even a single one — can cause authentication errors or failures in decoding.</strong></li></ol><h3>Conclusion</h3><p>Setting up CI/CD with Fastlane and GitHub Actions can significantly streamline your Flutter app deployment process. By automating repetitive tasks like versioning, building, and distributing APKs, you save time, reduce human error, and focus more on development. Once configured, deploying a new build becomes as simple as pushing code and triggering a workflow. This setup is especially helpful for teams aiming for faster feedback loops and more consistent releases. Happy shipping!</p><h3>Next Steps and Repository Link</h3><p>The complete code for this setup is available on GitHub in the <a href="https://github.com/AbhijithKonnayil/flutter-build-automation">part_1 branch</a>. This part covered the basic Fastlane setup for a Flutter project, including incrementing the build number and uploading the APK to Firebase App Distribution.</p><p>In the upcoming part, we’ll dive deeper into automating workflow triggers, customizing release notes, managing version names, and more advanced Fastlane features.</p><p>If this guide helped you, <strong>please give it a 👏 on Medium</strong> and <strong>follow for more Flutter + CI/CD content</strong>. Your support means a lot and keeps me motivated to create more valuable guides! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03dbc851ee8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Beginners’ Guide: Crafting Your First BMI Calculator App |Part 2]]></title>
            <link>https://abhijithkonnayil.medium.com/flutter-beginners-guide-crafting-your-first-bmi-calculator-app-part-2-2eda2e1a7070?source=rss-4c427139bef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2eda2e1a7070</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[bmi-calculator]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Abhijith K]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 16:54:41 GMT</pubDate>
            <atom:updated>2024-03-26T17:05:04.359Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s time to elevate our BMI calculator by enhancing the UI and adding exception handling. In this installment, we’ll focus primarily on UI modifications and incorporating neumorphic design elements.</p><p>To start, we’ll define a neumorphic decoration object that will be used in multiple places throughout our app. If you missed Part 1 of this tutorial, you can find it <a href="https://abhijithkonnayil.medium.com/flutter-beginners-guide-crafting-your-first-bmi-calculator-app-draft-070c5dc14dee">here</a>.</p><pre>class _HomePageState extends State&lt;HomePage&gt; {<br>  double? bmiValue;<br>  TextEditingController heightController = TextEditingController();<br>  TextEditingController weightController = TextEditingController();<br>  ....<br>  final BoxDecoration boxDecoration = BoxDecoration(<br>      color: Colors.grey[900],<br>      borderRadius: const BorderRadius.all(Radius.circular(10)),<br>      boxShadow: const [<br>        BoxShadow(color: Colors.black38, offset: Offset(5, 5), blurRadius: 10),<br>        BoxShadow(color: Colors.white12, offset: Offset(-5, -5), blurRadius: 10)<br>      ]);<br>  ....<br>}</pre><p>We’ve established a decoration object featuring a dark grey color scheme, border radius of 10, and two shadow variants — light and dark. This neumorphic design element will serve as a foundational component in enhancing the visual appeal of our BMI calculator app.</p><h4>Input Ui Modification</h4><pre>Widget buildInputUi() {<br>    return Column(<br>      mainAxisAlignment: MainAxisAlignment.center,<br>      children: [<br>        Container(<br>          height: 50,<br>          decoration: boxDecoration,<br>          child: TextField(<br>            cursorColor: Colors.white60,<br>            style: const TextStyle(color: Colors.white70),<br>            controller: heightController,<br>            decoration: const InputDecoration(<br>                border: OutlineInputBorder(borderSide: BorderSide.none),<br>                hintText: &quot;Height in cm&quot;,<br>                hintStyle: TextStyle(color: Colors.white24)),<br>          ),<br>        ),<br>        const SizedBox(<br>          height: 50,<br>        ),<br>        Container(<br>          height: 50,<br>          decoration: boxDecoration,<br>          child: TextField(<br>            cursorColor: Colors.white60,<br>            style: const TextStyle(color: Colors.white70),<br>            controller: weightController,<br>            decoration: const InputDecoration(<br>                hintText: &#39;Weight in Kg&#39;,<br>                border: OutlineInputBorder(borderSide: BorderSide.none),<br>                hintStyle: TextStyle(color: Colors.white24)),<br>          ),<br>        ),<br>        const SizedBox(<br>          height: 50,<br>        ),<br>        Container(<br>          decoration: boxDecoration,<br>          child: MaterialButton(<br>            height: 60,<br>            shape: const RoundedRectangleBorder(<br>              borderRadius: BorderRadius.all(Radius.circular(10)),<br>            ),<br>            minWidth: double.infinity,<br>            onPressed: calculateBMI,<br>            child: Text(<br>              &quot;CALCULATE BMI&quot;,<br>              style: TextStyle(<br>                  color: Colors.green[200],<br>                  fontSize: 16,<br>                  fontWeight: FontWeight.bold),<br>            ),<br>          ),<br>        )<br>      ],<br>    );<br>  }</pre><p>We’ve wrapped each text field and button with a Container and applied the decoration we created. For the text fields, we&#39;ve added border: OutlineInputBorder(borderSide: BorderSide.none) to remove the border, and also applied text styles for the text and hint text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMZP_Ok2mSXbuFuUZNt1vA.png" /></figure><h4>Output UI Modification</h4><p>To display the BMI value, we’ll utilize the percent_indicator package(Link : <a href="https://pub.dev/packages/percent_indicator">https://pub.dev/packages/percent_indicator</a>). You can add this package to our project using the following command</p><pre>flutter pub add percent_indicator</pre><p>Next, we’ll integrate a LinearPercentIndicator from the percent_indicator package. Since we&#39;re not displaying a percentage but rather the BMI range (18.5–30), we perform a small calculation to convert it accordingly. The LinearPercentIndicator accepts values between 0 and 1 only, so we calculate the value as follows: ((indicatorValue - 18.5) * 8.70 / 100). Additionally, to ensure that the indicator value falls within the BMI range of 18.5 to 30, we limit its value accordingly:</p><p>The rest of the implementation is similar to the input UI, with the addition of using a gradient to indicate the safe range of BMI.</p><pre> Widget buildOutputUi() {<br>    double indicatorValue = bmiValue!;<br>    if (indicatorValue &gt;= 30.0) {<br>      indicatorValue = 29.99;<br>    } else if (indicatorValue &lt;= 18.5) {<br>      indicatorValue = 18.6;<br>    }<br>    return Column(<br>      mainAxisAlignment: MainAxisAlignment.center,<br>      children: [<br>        Container(<br>          width: double.infinity,<br>          height: 50,<br>          alignment: Alignment.center,<br>          decoration: boxDecoration,<br>          child: Text(<br>            &quot;BMI : ${bmiValue!.toStringAsFixed(1)}&quot;,<br>            style: TextStyle(color: Colors.white70, fontSize: 28),<br>          ),<br>        ),<br>        const SizedBox(<br>          height: 25,<br>        ),<br>        Container(<br>          height: 50,<br>          decoration: boxDecoration,<br>          child: Container(<br>            decoration: BoxDecoration(<br>                borderRadius: BorderRadius.circular(10),<br>                gradient: LinearGradient(colors: [<br>                  Colors.lightBlue.withOpacity(0.75),<br>                  Colors.green.withOpacity(0.75),<br>                  Colors.yellow.withOpacity(0.75),<br>                  Colors.red.withOpacity(0.75)<br>                ])),<br>            child: LinearPercentIndicator(<br>              barRadius: Radius.circular(10),<br>              lineHeight: 12,<br>              linearGradient:<br>                  LinearGradient(colors: [Colors.purple, Colors.purple[300]!]),<br>              animation: true,<br>              percent: ((indicatorValue - 18.5) * 8.70 / 100),<br>            ),<br>          ),<br>        ),<br>        const SizedBox(<br>          height: 50,<br>        ),<br>        Container(<br>          decoration: boxDecoration,<br>          child: MaterialButton(<br>            height: 60,<br>            shape: const RoundedRectangleBorder(<br>              borderRadius: const BorderRadius.all(Radius.circular(10)),<br>            ),<br>            minWidth: double.infinity,<br>            onPressed: checkAnother,<br>            child: Text(<br>              &quot;CHECK ANOTHER&quot;,<br>              style: TextStyle(<br>                  color: Colors.green[200],<br>                  fontSize: 16,<br>                  fontWeight: FontWeight.bold),<br>            ),<br>          ),<br>        )<br>      ],<br>    );<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cV4R4rNCNEV0-6YDiBxGeQ.png" /></figure><h4>calculateBMI()</h4><p>In the calculateBMI() function, the issue lies in the absence of exception handling. If the user inputs an invalid value, it may lead to an error and app crash. To address this, we&#39;ll add a try-catch block to handle errors. In the catch section, we&#39;ll implement a showDialog to inform the user about the error gracefully</p><pre>void calculateBMI() {<br>    //bmi =  Formula: weight (kg) / [height (m)]^2<br>    try {<br>      double h = double.tryParse(heightController.text)! / 100;<br>      double w = double.tryParse(weightController.text)!;<br><br>      setState(() {<br>        bmiValue = w / (h * h);<br>      });<br>    } catch (e) {<br>      showDialog(<br>          context: context,<br>          builder: (_) {<br>            return Dialog(<br>              shape: RoundedRectangleBorder(<br>                  borderRadius: BorderRadius.circular(10)),<br>              backgroundColor: Colors.grey[900],<br>              child: Container(<br>                  padding: EdgeInsets.all(25),<br>                  child: const Text(<br>                    &quot;Invalid values for height or weight&quot;,<br>                    style: TextStyle(color: Colors.redAccent, fontSize: 18),<br>                  )),<br>            );<br>          });<br>    }<br>  }</pre><h4>build()</h4><p>In the modified build method, we&#39;ve improved the visual layout of our BMI calculator app. The Scaffold sets up the basic screen structure, while SafeArea ensures content is within the safe area. A Column organizes UI elements vertically, including a prominent title. The Container dynamically renders either input or output UI based on bmiValue, enhancing user interaction.</p><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      backgroundColor: const Color.fromRGBO(33, 33, 33, 1),<br>      body: SafeArea(<br>          child: SizedBox(<br>        width: double.infinity,<br>        child: Column(<br>            mainAxisAlignment: MainAxisAlignment.spaceAround,<br>            crossAxisAlignment: CrossAxisAlignment.center,<br>            children: [<br>              const Text(<br>                &quot;BMI CALCULATOR&quot;,<br>                style: TextStyle(<br>                  color: Colors.white,<br>                  fontSize: 42,<br>                ),<br>              ),<br>              Container(<br>                width: 360,<br>                alignment: Alignment.center,<br>                padding: const EdgeInsets.all(8.0),<br>                child: bmiValue == null ? buildInputUi() : buildOutputUi(),<br>              ),<br>            ]),<br>      )),<br>    );<br>  }</pre><p>As you conclude this tutorial, remember that this is just the beginning of your journey in Flutter development. While we’ve made significant improvements to our BMI calculator app, there’s still much more to explore and learn. Keep pushing your boundaries, experimenting with new concepts, and expanding your skills. This tutorial serves as a stepping stone towards your goals, and there’s a vast world of possibilities waiting for you to explore.</p><p>Source code : <a href="https://github.com/AbhijithKonnayil/bmi_calculator">https://github.com/AbhijithKonnayil/bmi_calculator</a><br>you can access the tutorial in the part-2 branch.</p><p>If you found this tutorial helpful and enjoyed building your first BMI calculator app with Flutter, please consider giving it an applause on Medium and starring the repository on GitHub. Your support encourages me to create more content to assist you on your Flutter development journey. Thank you for your support, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2eda2e1a7070" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Beginners’ Guide: Crafting Your First BMI Calculator App |Part 1]]></title>
            <link>https://abhijithkonnayil.medium.com/flutter-beginners-guide-crafting-your-first-bmi-calculator-app-draft-070c5dc14dee?source=rss-4c427139bef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/070c5dc14dee</guid>
            <dc:creator><![CDATA[Abhijith K]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 10:25:10 GMT</pubDate>
            <atom:updated>2024-03-26T17:02:00.793Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the exciting world of Flutter development! In this article, I’ll take you through my journey of creating a <strong>BMI Calculator</strong> app using Flutter. Whether you’re a newcomer to Flutter or have some prior experience, I invite you to join me as we delve into the process together. Let’s dive in and uncover the valuable insights we can gain along the way!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Styarg_ADBPtx_URRpJZg.png" /></figure><p>To create a new Flutter project, you can use the flutter create command followed by the name of your project. Here&#39;s how you can do it:</p><pre>flutter create bmi_calculator</pre><p>Open <strong>bmi_calculator</strong> project folder in vscode. Since we are creating from scratch, delete all the content of <em>main.dart</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r1nAJgvU3Cc-hWDGbjM3Jw.png" /></figure><p>Before getting into coding , if you need to know about the files and folder structure read this article. <a href="https://www.geeksforgeeks.org/flutter-file-structure/">https://www.geeksforgeeks.org/flutter-file-structure/</a></p><p>Let’s kickstart our Flutter project by establishing the entry point with the main function. In Flutter, the main function acts as the driver function, initiating the execution of our application. Within the main function, we utilize the runApp function to attach a widget to the screen, serving as the root widget of our application. While runApp requires a widget as its argument, we&#39;ll pass MyApp, which we&#39;ll create shortly. Although it may initially display an error due to the absence of the MyApp widget, we&#39;ll promptly address this in the subsequent steps of our development process. Let&#39;s proceed to define MyApp and bring our BMI Calculator app to life!</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(MyApp());<br>}</pre><p>Now, let’s proceed to create our root widget, MyApp. In Flutter, most custom widgets are implemented as classes that extend either StatelessWidget or StatefulWidget. For MyApp, we&#39;ll create a class that extends StatelessWidget. Within this class, we&#39;ll define a build() method, which encapsulates the UI components to be displayed on the screen.</p><p>In this implementation, we’ll return a MaterialApp widget, an integral part of Flutter that leverages Material Design principles for the application&#39;s user interface. Additionally, we&#39;ll set the home property of MaterialApp to HomePage, the subsequent widget we&#39;ll create. This straightforward approach establishes HomePage as the initial page displayed when the application is launched. Let&#39;s proceed to define MyApp and lay the foundation for our BMI Calculator app.</p><pre>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return const MaterialApp(home: HomePage(),);<br>  }<br>}</pre><p>Now, let’s proceed to create our home page. Begin by creating a new file named home_page.dart in the same location as main.dart. Alternatively, you can choose to define the HomePage widget within the same file as main.dart, depending on your project structure preferences.</p><p>Within home_page.dart, we&#39;ll define a class named HomePage that extends StatefulWidget. Unlike MyApp, HomePage requires state management, indicating that we may need to rebuild the page to display different UI elements at various points in time.</p><p>The HomePage widget consists of two classes: HomePage, representing the widget itself, and _HomePageState, representing the state of HomePage. The build() method, responsible for defining the UI components, resides within the state class. Let&#39;s proceed to define HomePage and its corresponding state to further advance our BMI Calculator app development.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>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>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold();<br>  }<br>}</pre><p>Ensure home_page.dart is imported into main.dart if HomePage is defined in a separate file.</p><pre>import &#39;package:bmi_calculator/home_page.dart&#39;;</pre><p>Now, let’s run our app using the flutter run command.</p><pre>flutter run</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-oI-HZ9lvm5yKztHX-KCg.png" /></figure><p>Upon running the app, you’ll be prompted to select a device from the list of connected devices. Depending on the platform you’re targeting, choose the appropriate device. For simplicity, let’s proceed with Chrome. This will open a Chrome window with no content displayed yet. However, there’s no need to worry as we’re about to create the user interface (UI) for our app. Let’s move forward and design the UI components for our BMI Calculator app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BfKouyGMY-BwWoRx8l9fBw.png" /></figure><p>After initiating the app, you’ll notice a message in the terminal, typically highlighted in red, indicating that any changes made to the UI will require a refresh to reflect them on your device (in this case, the browser). To trigger a refresh, simply press the ‘r’ or ‘R’ key in the terminal. This quick shortcut ensures that any modifications you make to the UI are promptly updated and visible on your device. Let’s keep this in mind as we proceed with designing and refining our BMI Calculator app’s user interface.</p><h3>User Interface</h3><p>Now lets discuss about the minimal user interface required for our bmi calculator. What all be need ?Lets list down.<br>We need two UIs , one to take inputs and the other to show the outputs.</p><h4>Input Ui</h4><p>1. User input field for height<br>2. User input field for Weight<br>3. A button to initiate calculation</p><h4>Output Ui</h4><ol><li>the BMI value</li></ol><h3>State</h3><p>We created the HomePage as StatefulWidget and mentioned that a state will be associated with it. What is the state here ?</p><p>Lets put it this way, what is thing that decides which UI should be rendered on the screen ? Yes , its the BMI value. <br>If we have BMI value → display the BMI value (output ui) , <br>otherwise → ui to collect the details to calculate the bmi value(input ui).</p><h3>Fields and Methods</h3><p>Lets now list down what are the methods and fields</p><h4>Fields and datatypes</h4><p>bmiValue : double → to store bmi value<br>heightController, weightController : TextEditingController → to access the value in corresponding text field</p><h4>Methods</h4><p>calculateBMI() → to calculate the bmi and update the ui<br>checkAnother() → to reset the values and check again<br>buildInputUi() → to build the input ui<br>buildOutputUi() → to build the output ui</p><h3>Lets Start Coding</h3><p>Now we have idea on the UIs, State and associated fields and methods to build out application.</p><p>Lets define the fields inside the _HomePageState,</p><pre>class _HomePageState extends State&lt;HomePage&gt; {<br>...<br>...<br>double? bmiValue;<br>TextEditingController heightController = TextEditingController();<br>TextEditingController weightController = TextEditingController();<br>...<br>...<br>}</pre><p>Now lets define the methods one by one</p><p><strong>buildInputUi()</strong><br>the input ui requirement can be build with a Column ,TextFields for height and weight and a MaterailButton.To keep the UI simple and functional, we’ll implement only the essential components necessary for the BMI calculation functionality.</p><pre>Widget buildInputUi() {<br>    return Column(<br>      children: [<br>        TextField(<br>          controller: heightController,<br>          decoration: InputDecoration(hintText: &quot;Height in cm&quot;),<br>        ),<br>        TextField(<br>          controller: weightController,<br>          decoration: InputDecoration(hintText: &#39;Weight in Kg&#39;),<br>        ),<br>        MaterialButton(<br>          color: Colors.greenAccent,<br>          onPressed: calculateBMI,<br>          child: Text(&quot;Calculate BMI&quot;),<br>        )<br>      ],<br>    );<br>  }</pre><p><strong>Column</strong> → takes a list of widgets as children and render it one below the other<br><strong>TextField</strong> → allows user to input values and allows us to attach a controller to it, the user input value can be accessed with that controller. The decoration property allows us to modify the appearance of the text field with hint, label, border etc<br><strong>MaterialButton</strong> → display a button and have onPressed property where we can give the function to be executed when user clickes on the button. The text or icons to be displayed on the button can be passes as child. Here, its <strong>calculateBMI() , </strong>we will create that function later</p><p><strong>buildOutputUi()<br></strong>Output ui is nothing different from input ui. We use a Column, Text to display the value and a MaterialButton to reset and check another.</p><pre>Widget buildOutputUi() {<br>    return Column(<br>      children: [<br>        Text(&quot;$bmiValue&quot;),<br>        MaterialButton(<br>          color: Colors.greenAccent,<br>          onPressed: checkAnother,<br>          child: Text(&quot;Check Another&quot;),<br>        )<br>      ],<br>    );<br>  }</pre><p><strong>calculateBMI()<br></strong>When calculating BMI, we use the formula: weight (kg) / [height (m)]². Since the values accessed from the text editing controller are strings, we parse them into double data types. It’s important to note the “!” operator, indicating to Flutter that we’re asserting the non-nullability of the value returned by double.parse(). While proper exception handling should be included, we&#39;ll defer this for now.</p><p>Later on, we&#39;ll revisit and refine this function as needed.</p><pre><br>void calculateBMI() {<br>    //BMI Formula: weight (kg) / [height (m)]^2<br>    double h = double.tryParse(heightController.text)!/100;<br>    double w = double.tryParse(weightController.text)!;<br>    bmiValue = w / (h*h);<br>    print(&quot;BMI : $bmiValue&quot;);<br>  }</pre><p><strong>checkAnother()<br></strong>For resetting the UI and values, we clear all the values the fields.</p><pre><br>  void checkAnother() {<br>    heightController.text = &quot;&quot;;<br>    weightController.text = &quot;&quot;;<br>    bmiValue = null;<br>  }</pre><p>Now that we’ve defined all the necessary fields and methods, it’s time to run the app. Before doing so, let’s add the body to our scaffold to display the input UI.</p><pre>Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: buildInputUi(),<br>    );<br>  }</pre><p>Now, run the app using flutter run. Input the height and weight to calculate the BMI. Although the UI won&#39;t visibly change, you can observe the calculated BMI value printed in the terminal. This confirms that the functionality is working correctly, even though the UI remains static for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7vICsDQqLIgyAWEau2O_Q.png" /></figure><p>Let’s address this step by step. Firstly, we need to adjust the Scaffold to render buildOutputUi if bmiValue contains a valid BMI value. Otherwise, we&#39;ll render buildInputUi. We can implement this logic using the conditional operator to dynamically determine which UI to display based on the presence of the BMI value. Let&#39;s proceed with implementing this logic.</p><pre>@override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: bmiValue==null?buildInputUi():buildOutputUi(),<br>    );<br>  }</pre><p>After making this adjustment, reload the app. Initially, you should see the input UI. Then, assign a value to bmiValue (line no. 13 in the code snippet provided) and reload the app again. This time, you&#39;ll observe the output UI displayed. Once you&#39;ve tested the functionality, remember to undo the change made to bmiValue to maintain the original state of the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ABjZykzvXPFZBsE4XfjcQ.png" /></figure><p>so lets list down the observations.</p><ol><li>Initially, the app displays the input UI.</li><li>Upon invoking calculateBMI(), the BMI is calculated and bmiValue is updated, but the UI remains unchanged.</li><li>When assigning an initial value to bmiValue, the output UI is rendered.</li></ol><p>The missing piece here is that although bmiValue is updated, the UI doesn&#39;t reflect this change. This is because we need to inform Flutter to rebuild the UI once the state changes. We accomplish this using the setState((){}) function, which notifies the Flutter framework that the state has changed and triggers a rebuild of the UI by calling the build() method again. Let&#39;s update the methods to incorporate the use of setState().</p><pre>void calculateBMI() {<br>    //bmi =  Formula: weight (kg) / [height (m)]^2<br>    double h = double.tryParse(heightController.text)! / 100;<br>    double w = double.tryParse(weightController.text)!;<br>    <br>    setState(() {<br>     bmiValue = w / (h * h);<br>    });<br>  <br>  }<br><br>  void checkAnother() {<br><br>    setState(() {<br>      heightController.text = &quot;&quot;;<br>      weightController.text = &quot;&quot;;<br>      bmiValue = null;<br>    });<br>  }</pre><p>There you have it! Our basic BMI calculator is now complete. While it’s functional, there’s still room for improvement. The UI could be enhanced, and exception handling needs to be implemented. These aspects will be addressed in the next stage.</p><p>If you’re interested in taking our BMI calculator to the next level, <a href="https://abhijithkonnayil.medium.com/flutter-beginners-guide-crafting-your-first-bmi-calculator-app-part-2-2eda2e1a7070">follow the part 2 here</a></p><p>Source code : <a href="https://github.com/AbhijithKonnayil/bmi_calculator">https://github.com/AbhijithKonnayil/bmi_calculator</a><br>you can access Part 1 of the tutorial in the part-1 branch.</p><p>If you found this tutorial helpful and enjoyed building your first BMI calculator app with Flutter, please consider giving it an applause on Medium and starring the repository on GitHub. Your support encourages me to create more content to assist you on your Flutter development journey. Thank you for your support, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=070c5dc14dee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Multi-App Projects in Flutter: The Power of Shared Packages]]></title>
            <link>https://abhijithkonnayil.medium.com/streamlining-multi-app-projects-in-flutter-the-power-of-shared-packages-28c9e577449b?source=rss-4c427139bef9------2</link>
            <guid isPermaLink="false">https://medium.com/p/28c9e577449b</guid>
            <category><![CDATA[flutter-package]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Abhijith K]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 11:50:13 GMT</pubDate>
            <atom:updated>2023-08-16T11:50:13.415Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re here, chances are you’re already familiar with the power of Flutter. You’ve experienced its ability to breathe life into app interfaces and create seamless user experiences.While there are tutorials that help you learn to create apps in Flutter, there’s a gap when it comes to handling big projects. This article delves into a specific challenge we encounter in such scenarios. We’re taking a closer look at a problem that arises when dealing with more complex, multi-app projects — the kind where multiple interconnected apps coexist within one major endeavour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yrwp2LJtk3qa-VGt" /></figure><h3>Why Do We Need Shared Packages?</h3><p>Think about projects that include different apps, like an admin app alongside an app for customers. Or consider apps that serve various purposes, like Swiggy’s delivery app, partner app, and delivery partner app. You can even imagine different versions of the same app, like regular Facebook and the lighter Facebook Lite.</p><p>Shared packages in Flutter offer a robust solution to a common challenge faced during app development: the need to maintain consistency and reduce redundancy across multiple applications. Let’s explore a practical scenario to understand why shared packages are essential and how they can significantly benefit development efforts.</p><h4>Example: Building a Multi-App Restaurant Platform</h4><p>Imagine you’re tasked with developing a comprehensive restaurant platform comprising three separate apps:</p><ol><li>Customer App: The customer app enables users to browse menus, place orders, and track deliveries.</li><li>Manager App: The manager app facilitates order management, inventory control, and coordination with the kitchen.</li><li>Delivery App: The delivery app empowers drivers to view delivery assignments, navigate routes, and update order statuses.</li></ol><p>While the functionality varies across these apps, they all share certain commonalities:</p><p><strong>Uniform Branding and Theme</strong>: All three apps need a consistent branding, typography, color scheme, and overall user interface design. Replicating these across three separate projects would be time-consuming and prone to inconsistencies.</p><p><strong>Reusable Widgets and Components:</strong> Elements like custom buttons, navigation bars, and user profile displays might be used across all three apps. Rebuilding these widgets in each project introduces redundancy and increases maintenance efforts.</p><p><strong>Common Logic and Business Rules:</strong> While the specific functionalities vary, some core business rules might apply to all apps, such as user authentication, data validation, and API communication.</p><p><strong>The Challenge without Shared Packages: Duplication and Maintenance Struggles</strong></p><ol><li><strong>Redundant Efforts:</strong> Creating separate instances of the same UI components, themes, and logic across multiple apps results in redundant work.</li><li><strong>Inconsistencies: </strong>Manual replication of resources can lead to inconsistencies in branding, styling, and functionality, ultimately affecting user trust and experience.</li><li><strong>Complex Maintenance:</strong> Updating shared resources, such as modifying a theme or widget, requires implementing the same changes across all apps, leading to increased complexity and room for errors.</li></ol><p>In the restaurant platform example, a shared package could encompass branding assets, UI components, and core business logic. Each app would then integrate this shared package, facilitating rapid updates and mitigating the challenges of maintaining consistent resources.</p><h3>Creating a Shared Package: The Foundation for Reusability</h3><p>A shared package is a standalone Dart library that encapsulates reusable components, logic, and resources. To set the foundation for reusability, follow these steps:</p><h4><strong>Create the Package</strong></h4><p>Open a terminal and navigate to the directory where you want to create your package. Use the following command to create a new package:</p><blockquote>flutter create — template=package package_name</blockquote><h4>Define Common Elements</h4><p>Identify the components, widgets, repositories, and functions that are common across your apps. Place these elements within the shared package, ensuring they’re isolated and can be reused seamlessly.</p><h4>Version and Document</h4><p>Maintain version control for your shared package using a tool like Git. Proper versioning and documentation are crucial for effective collaboration and understanding how to integrate the package into apps</p><h3>Integrating the Shared Package: Local and Remote Approaches</h3><p>Once you’ve crafted your shared package, it’s time to integrate it into your apps. Two primary integration methods are available: local linking and remote linking.</p><h4>1. Local Linking:</h4><p>Local linking involves referencing the shared package’s local path in your app’s pubspec.yaml file. This approach is ideal when you&#39;re the primary developer or working in a closed environment.</p><p><strong>Link the Package:</strong> In your app’s pubspec.yaml, add the shared package as a dependency, specifying the local path:</p><blockquote>dependencies:<br> flutter:<br> sdk: flutter<br> <strong>custom_package_name:<br> path: path/to/package</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*c21vgvDE-Qkthycf9PFC9Q.png" /></figure><p><strong>Use Relative Paths:</strong> Use a relative path for the package’s location. This ensures consistency across different development environments and avoids path conflicts when collaborating with teammates.</p><h4>2. Remote Linking:</h4><p>Remote linking involves referencing the shared package’s Git repository in your app’s pubspec.yaml file. This approach is suitable for larger teams and open-source projects.</p><p><strong>Link the Package: </strong>In your app’s pubspec.yaml, add the shared package as a dependency, specifying the Git repository URL and branch reference:</p><blockquote>dependencies:<br> flutter:<br> sdk: flutter<br> <strong>common_package:<br> git:<br> url: </strong><a href="https://github.com/path/to/common_package.git"><strong>https://github.com/path/to/common_package.git</strong></a><strong><br> ref: master</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*5qjB3STyC7pX-wXzMsC9Ww.png" /></figure><p><strong>Collaboration Made Easy:</strong> This approach promotes collaboration by allowing multiple developers to work on the package independently. Updates made by various team members are seamlessly reflected in the remote repository.</p><h3>Benefits of Shared Packages:</h3><ol><li><strong>Consistency: </strong>Common resources like themes, widgets, and functions are maintained consistently across all apps that use the shared package.</li><li><strong>Reduced Redundancy:</strong> Avoid duplicating code and resources by centralizing them in the shared package.</li><li><strong>Simplified Maintenance:</strong> Updates to shared elements only need to be made in one place, reducing the chances of inconsistencies.</li><li><strong>Efficient Collaboration:</strong> Teams can work on the package independently, and updates are easily integrated through version control.</li><li><strong>Flexibility:</strong> Depending on your development needs, you can choose between local and remote linking approaches.</li></ol><p>Flutter’s flexibility extends beyond building standalone apps; it also provides a powerful way to manage shared resources through packages. By creating a shared package and integrating it into multiple apps, you can maintain consistency, reduce redundancy, and streamline maintenance. Whether you’re a solo developer or part of a team, embracing shared packages will accelerate your app development journey and foster collaboration among your peers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28c9e577449b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>