<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Saurabh Pant on Medium]]></title>
        <description><![CDATA[Stories by Saurabh Pant on Medium]]></description>
        <link>https://medium.com/@saurabhpant?source=rss-2d75d9ffef06------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ts2ALdSfD6KiIkoYjTTMfQ.png</url>
            <title>Stories by Saurabh Pant on Medium</title>
            <link>https://medium.com/@saurabhpant?source=rss-2d75d9ffef06------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 05:39:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saurabhpant/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[A Trip from Delhi to Malaysia: What When and How?]]></title>
            <link>https://medium.com/so-sauri/a-trip-from-delhi-to-malaysia-what-when-and-how-ea3e47733349?source=rss-2d75d9ffef06------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea3e47733349</guid>
            <category><![CDATA[tourism]]></category>
            <category><![CDATA[malaysia]]></category>
            <category><![CDATA[langkawi]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[budget-travel]]></category>
            <dc:creator><![CDATA[Saurabh Pant]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 13:16:56 GMT</pubDate>
            <atom:updated>2025-07-30T13:16:56.179Z</atom:updated>
            <content:encoded><![CDATA[<h4>Travel Blog</h4><h4>Malaysia Truly Asia!</h4><p>We’ve been to Malaysia twice, Yes twice! Because we love this country’s vibe, culture, affordability and there is a lot to do in here for everyone. We’ll probably go to Malaysia again super soon. Watch out 🤭</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MU2tv8ee4crCLsibf5_BLg.jpeg" /><figcaption>Langkawi Island, Malaysia</figcaption></figure><h3>So Underrated and Ignored</h3><p>To our surprise, this is so ignored destination in Indians. One of the major reason could be that there is no proper and collected details available on Malaysia over one place. So as usual it become tough to plan such a wonderful destination even when it could have given you an international stamp already.</p><p>Another reason we believe is that Malaysia has never been glamourised much on social media yet.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPVdJpvLcu1Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FPVdJpvLcu1Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPVdJpvLcu1Y%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cec1340cf65e98778c4bab738d98ee74/href">https://medium.com/media/cec1340cf65e98778c4bab738d98ee74/href</a></iframe><h3>Answering to Questions that Matter</h3><p>In this blog we’ll share details on</p><ol><li>Why we chose Malaysia?</li><li>What we we liked most about Malaysia?</li><li>When we went there?</li><li>What was my our person budget with break up?</li><li>How we applied for VISA?</li><li>What all places we visited?</li><li>Is it worth visiting with whole Family?</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiM1IMlV9KfU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FiM1IMlV9KfU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiM1IMlV9KfU%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/30f37a392d30a678ff7a839ae920a4ff/href">https://medium.com/media/30f37a392d30a678ff7a839ae920a4ff/href</a></iframe><h3>Why We Chose Malaysia?</h3><p>When we were searching for our next international destination, we landed on Malaysia on the Google Maps.</p><p>We chose Malaysia for the following reasons:</p><ol><li>Flights are very affordable</li><li>Easy VISA process</li><li>Stays are so beautiful, spacious and reasonably priced</li><li>Currency conversion is not high. 1 Malaysian Rinngit = ~INR 20</li><li>Lot of sightseeing and greenery everywhere, from high rise towers to lakes, from off beat destinations to food and shopping and what not</li><li>Have its duty free Island, Langkawi where you can spend time on clean beaches and try your luck at the casino [We doubled on our bet 😉]</li></ol><p>I think these are enough and strong reasons for anyone to travel to Malaysia.</p><blockquote><strong>Verdict: Must have a look for a plan to Malaysia</strong></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FftEA8cMYzpg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FftEA8cMYzpg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FftEA8cMYzpg%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9972f7c6a3744c28addaf8ae5d10c3a/href">https://medium.com/media/f9972f7c6a3744c28addaf8ae5d10c3a/href</a></iframe><h3>What we we liked most about Malaysia?</h3><p>As per our experience, we liked the following</p><ul><li>Its Night Street Markets where you can shop like a local</li><li>Its Food Streets which are a delight for Non-Vegetarians</li><li>Its Highlands, High Rise Towers and the so beautiful routes while going there</li><li>Lust Greenery everywhere and literally everywhere and we were so amazed with it</li><li>LEGOLAND in Johor Bahru for kids</li><li>Its Duty Free Island — Langkawi which is a must visit and could be your Finisher of the Malaysia tour</li></ul><blockquote><strong>Verdict: We loved being in Malaysia and we’re sure that you would love it too.</strong></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQHQMfK-4P9E%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FQHQMfK-4P9E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQHQMfK-4P9E%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c1c8707737812fe5aacc9cefcb8388f/href">https://medium.com/media/5c1c8707737812fe5aacc9cefcb8388f/href</a></iframe><h3>When we went there?</h3><p>We went Malaysia twice.</p><ol><li>First we went in Aug-Sep 2022 for 12 days. Both of us went to celebrate our One and Half year Anniversary.</li><li>Second time we went in May-Jun 2025 for 8 days and this time we took our families together. We were 8 people and age range was 3 year old to 54 year old.</li></ol><blockquote><strong>Verdict: You can visit anytime between May to Sep overall.</strong></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbMi7AYTPLoY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FbMi7AYTPLoY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FbMi7AYTPLoY%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a839812f381eb33de8cb02b2604b5c7c/href">https://medium.com/media/a839812f381eb33de8cb02b2604b5c7c/href</a></iframe><h3>Our Per Person Budget</h3><p>For a 12 days tour, Our fixed cost included</p><ul><li>Flights: <strong>INR 20,000</strong></li><li>Stay: <strong>INR 17,500</strong></li><li>VISA: <strong>INR 3500</strong></li></ul><p>Our variable cost included</p><ul><li>Food: <strong>INR 8,000</strong></li><li>Tours/Experiences: <strong>INR 20,000</strong></li></ul><p>Total: ~<strong>INR 70,000</strong></p><p>Your budget could easily be lower than ours if you plan for 5 to 7 days.</p><blockquote><strong>Verdict: Super affordable for a 5 days tour or even longer. Must GOOOO!!!!</strong></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTEc2nc-Rk2s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FTEc2nc-Rk2s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTEc2nc-Rk2s%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/84d4935d1491246358ec4eb48b61fd7b/href">https://medium.com/media/84d4935d1491246358ec4eb48b61fd7b/href</a></iframe><h3>How we applied for VISA?</h3><p>In 2022, there was a VISA requirement to travel to Malaysia. But in 2025, travelling to Malaysia is <strong>VISA FREEEEEEE</strong> 🤭.</p><blockquote><strong>Verdict: Do we need to insist more???</strong></blockquote><h3>What all places we visited?</h3><p>During our time in Malaysia, we managed to cover the following</p><ul><li>Kuala Lumpur<br>- Twin Tower<br>- KL Tower<br>- Petaling Street<br>- Jalan Alor Street</li><li>Batu Caves</li><li>Chin Swee Temple</li><li>Genting Highlands</li><li>Cameron Highlands</li><li>Melacca City</li><li>LEGOLAND in Johor Bahru</li><li>Penang</li><li>Langkawi Island</li></ul><p>There were places within these cities and island that we visited and aren’t listed here. Otherwise the list would be very long.</p><blockquote><strong>Verdict: Lot to see and experience. <br>Comment in this blog or reach out to us on </strong><a href="https://www.instagram.com/so_sauri"><strong>Instagram</strong></a><strong> to know more.</strong></blockquote><h3>Is it worth visiting with whole Family?</h3><p>We would only say YES!!!</p><p>We went there second time with our family only and because we loved being here the first time. So much to see for everyone. Even the kid with us enjoyed more than us. The apartment we stayed in was super cool.</p><p>So don’t think twice, pack your bags and lets gooooooo.</p><p>Byeeeeee and have a great trip to Malaysiaaaaaa 😉</p><blockquote><strong>Verdict: 100%</strong></blockquote><p><a href="https://www.instagram.com/reel/DKUqtVhPupt/">https://www.instagram.com/reel/DKUqtVhPupt</a></p><h3>That is all for now! Stay tuned!</h3><p>Connect with us on</p><ul><li>Instagram: <a href="https://www.instagram.com/so_sauri">https://www.instagram.com/so_sauri</a></li></ul><p>Until we go on our next destination…</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea3e47733349" width="1" height="1" alt=""><hr><p><a href="https://medium.com/so-sauri/a-trip-from-delhi-to-malaysia-what-when-and-how-ea3e47733349">A Trip from Delhi to Malaysia: What When and How?</a> was originally published in <a href="https://medium.com/so-sauri">So_Sauri</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Trip from Delhi to Georgia : What When and How?]]></title>
            <link>https://medium.com/so-sauri/a-trip-from-delhi-to-georgia-what-when-and-how-3c4efc83f5e4?source=rss-2d75d9ffef06------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c4efc83f5e4</guid>
            <category><![CDATA[food]]></category>
            <category><![CDATA[georgia]]></category>
            <category><![CDATA[europe]]></category>
            <category><![CDATA[nature]]></category>
            <category><![CDATA[travel]]></category>
            <dc:creator><![CDATA[Saurabh Pant]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 16:45:18 GMT</pubDate>
            <atom:updated>2024-12-07T17:13:05.185Z</atom:updated>
            <content:encoded><![CDATA[<h4>Travel Blog</h4><h3>A Trip from Delhi to Georgia : What When and How?</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FfSyrsiTr0BY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FfSyrsiTr0BY%3Fsi%3DGnRc_ZY-wsKz1Hyj&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FfSyrsiTr0BY%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0971ebe77ed822dbff1de32c99b6e556/href">https://medium.com/media/0971ebe77ed822dbff1de32c99b6e556/href</a></iframe><p>I recently visited Georgia in eastern Europe. While exploring for my next travel destination, it was all very confusing and there is lot of information available based on various factors like budget, spots, accommodation, flights etc.</p><p>Instead of being easy, it is a lot difficult these days to plan a travel destination. So I thought to share my own experience with clear decisions and some data so that it can actually be easier for you to plan your trip.</p><p>In this blog I’ll share details on</p><ol><li>Why I chose Georgia?</li><li>What Georgia is famous for?</li><li>When I went there?</li><li>What was my per person budget with break up?</li><li>How I applied for VISA?</li><li>What all places I visited?</li><li>Is it worth visiting with whole Family?</li></ol><h3>Why I chose Georgia?</h3><p>At the start, I had only these reason to choose it honestly.</p><ul><li>Other countries were expensive and I had only one month time to plan for our half yearly anniversary.</li><li>Direct flight of ~5hrs</li><li>E-visa is available</li><li>Veg food is readily available and very tasty</li><li>Georgia is a small and very beautiful country and we could visit lot of places from its capital Tbilisi</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtxJRdrGjcTCZLCgQAg5pQ.png" /></figure><blockquote>Verdict:<strong><em> You MUST give it a travel, No matter what people says! Period!</em></strong></blockquote><h3>What Georgia is famous for?</h3><p>Initially what I knew is Georgia is world known for its Wine. Yes Wine. I drank a lot of different wines there and they all were Tasty.</p><p>Georgia is also famous for Khinkhali (top right) and Khachapuri (bottom right). I loved Khachapuri seriously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvK6gDY2sT9HsrywvTEJ8Q.png" /><figcaption>Photos by me</figcaption></figure><p>I saw the pictures of Georgia and it looked pretty in them but when I visited it, I was shocked to see that it is rather prettier in real than those pictures.</p><p>Lots of tourists, locals, singing and dancing on streets by locals, so much food to eat, walkable city to main areas, dramatic kind of streets with lots of Graffiti which looks weird at first sight but that’s how they are and finally a lovely weather and clean air and what not.</p><p>I just loved the vibe being there. It was so lively and you would feel it.</p><blockquote>Verdict:<strong><em> Don’t wait. Just book and leave!</em></strong></blockquote><h3>When I went there?</h3><p>The best time is around May-June and Sep-Oct as per google search but I went there from 22nd Aug to 3rd Sep 2024. Very pleasant weather.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_A2MHwCYDCA1sA7pYK8O5g.png" /><figcaption>Captured by me</figcaption></figure><blockquote>Verdict:<strong><em> Whenever you can, just visit. It’ll be worth visiting.</em></strong></blockquote><h3>What was my per person budget with break up?</h3><p>The trip to Georgia for 10 days cost me as follows</p><p>Fixed cost: <strong>INR 50,000</strong></p><ul><li>Flight: INR 30,000</li><li>Stay: INR 17,000</li><li>VISA: INR 3,000</li></ul><p>Variable cost: <strong>INR 40,000</strong></p><p>It included Food and other activities but I normally don’t track it because whatever is above my fixed cost is the combination of all these factors. Easier to track 😉</p><p>Except flights and visa cost which almost remain same, you can reduce the budget based on number of days you want to spend, stay you choose and what all activities, spots you want to visit. Lot of scope to get the budget in your pocket.</p><p>Believe me, there are so many stays offered at a lower cost. I was skeptical because there was no one to guide me but I’m telling you there a lot of options in stay available which are affordable and nice.</p><blockquote>Verdict:<strong><em> Choose your stay and duration wisely. As per my experience, at least 6 days should be chosen.</em></strong></blockquote><h3>How I applied for VISA?</h3><p>VISA can be applied directly from the website of Georgia government <a href="https://www.evisa.gov.ge/GeoVisa/">here</a>.</p><p>No need to apply visa any agent. It is very very straightforward.</p><blockquote>If you find any difficulty, let me know!</blockquote><p>Visa arrive within a week with either approval or rejection.</p><p>Three things I would emphasise on are</p><ol><li><strong><em>Make sure to match every detail as per your passport</em></strong>. I faced difficulty at the airport where my city of birth didn’t match with passport because I filled up New Delhi on the visa application whereas it was Delhi in my passport. So be very careful about these details.</li><li>Must attach bank statements with at least a current balance of INR 2 lakhs.</li><li>If you’ve <strong>UK or US visas</strong> previously, do attach them to make the application stronger.</li></ol><p>If you keep these things well updated then sit back and relax, you’ll get your visa for sure.</p><blockquote>Verdict:<strong><em> Apply yourself!</em></strong></blockquote><h3>What all places I visited?</h3><p>I always try to keep a balance between too much travel and leisure. So I went to places as much as I could but also keeping two days for just doing nothing and living like locally.</p><p>Here’s a list of places I visited within Tbilisi</p><ul><li>Narikala Fort</li><li>Bridge of peace</li><li>Chronicles of Georgia</li><li>Liberty Square</li><li>Mother of Georgia</li><li>The Clock Tower</li><li>Meidan Bazar</li><li>Old Tbilisi</li></ul><p>Here’s a list of cities I managed to visit in Georgia:</p><ul><li>Tbilisi</li><li>Kazbegi</li><li>Kutaisi</li><li>Gudauri</li><li>Sighnaghi</li><li>Borjomi</li><li>Kakheti</li><li>Uplistsikhe</li><li>Mtskheta</li></ul><blockquote>Verdict:<strong><em> Must visit Tbilisi, Kazbegi and Kutaisi. Rest of the cities can be covered in day tours side by side.</em></strong></blockquote><h3>Is it worth visiting with whole Family?</h3><p>If you take my words, <strong>Georgia is a MUST visit destination</strong> for an international tour with your family or friends or solo. It caters to everyone needs perfectly.</p><p>Just take care of your stay location if you’ve elder people with you because stays in Tbilisi are on a inclined slope which could be difficult to walk on for elder people.</p><blockquote>Verdict:<strong><em> Must visit. I would even recommend it over Azerbaijan.</em></strong></blockquote><h3>Conclusion</h3><p>Book your tickets and go to Georgia. Period!</p><blockquote>Checkout the reel</blockquote><blockquote>A Good Day in a #beautiful city 🏙️</blockquote><blockquote>#travel #tourism #europe #europetravel #day1 #georgia #tbilisi #vacations<br><a href="https://www.instagram.com/share/reel/BAG6XC2uvg">https://www.instagram.com/share/reel/BAG6XC2uvg</a></blockquote><h3>That is all for now! Stay tuned!</h3><p>Connect with me (if the content is helpful to you ) on</p><ul><li><a href="https://saurabhpant.medium.com/">Medium</a></li><li><a href="https://github.com/aqua30">GitHub</a></li><li><a href="https://twitter.com/saurabh30pant">Twitter</a></li><li><a href="https://www.linkedin.com/in/saurabh-pant-44619057/">LinkedIn</a></li><li><a href="https://www.youtube.com/@_zaqua">Youtube</a></li></ul><p>Until next time…</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c4efc83f5e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/so-sauri/a-trip-from-delhi-to-georgia-what-when-and-how-3c4efc83f5e4">A Trip from Delhi to Georgia : What When and How?</a> was originally published in <a href="https://medium.com/so-sauri">So_Sauri</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Import using Export in Flutter]]></title>
            <link>https://blog.devgenius.io/import-using-export-in-flutter-98d60f883190?source=rss-2d75d9ffef06------2</link>
            <guid isPermaLink="false">https://medium.com/p/98d60f883190</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Saurabh Pant]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 10:03:32 GMT</pubDate>
            <atom:updated>2024-11-20T15:21:38.072Z</atom:updated>
            <content:encoded><![CDATA[<h4>FLUTTER TUTORIAL</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LmmCi5NFAcZAEJz9LwsFg.png" /></figure><p>When a class has many dependencies on other ones, it quickly become a hassle to maintain the imports in the file. Imports may itself can take more than 150 to 200 lines and even more if a part of a larger project. Then arises a lot of maintainability issues.</p><p>This article will be about the use cases of <strong><em>export</em></strong> keyword in Flutter for clean code, maintainability and migration of classes.</p><h3>Use case 1: Cleaner imports</h3><p>Let’s consider we’ve a repository class which depends on four different types of model classes as follows</p><pre>import &#39;../model/model_a.dart&#39;;<br>import &#39;../model/model_b.dart&#39;;<br>import &#39;../model/model_d.dart&#39;;<br>import &#39;../model/model_c.dart&#39;;<br>...<br><br>class UserRepo {<br><br>  final ModelA a = ModelA();<br>  final ModelB b = ModelB();<br>  final ModelC c = ModelC();<br>  final ModelD d = ModelD();<br><br>  ...<br>}</pre><p>There might be many more. In a considerable big project, it can be a hassle to have so many imports in a class. Hence we can use export keyword here and create a new class as follows</p><pre>file: models_barrel.dart<br><br>export &#39;model_a.dart&#39;;<br>export &#39;model_b.dart&#39;;<br>export &#39;model_c.dart&#39;;<br>export &#39;model_d.dart&#39;;</pre><p>Generally, such types of classes are called as Barrel classes. Once created we can now replace of these imports in our UserRepo class as follows</p><pre>import &#39;../model/models_barrel.dart&#39;;<br><br>class UserRepo {<br>  <br>  final ModelA a = ModelA();<br>  final ModelB b = ModelB();<br>  final ModelC c = ModelC();<br>  final ModelD d = ModelD();<br><br>}</pre><p>We import this barrel class which exposes these classes’ access to our UserRepo. Hence this can help us in keeping our classes lean and clear.</p><h3>Use case 2: Class migration</h3><p>Taking the same UserRepo example above, we would want to replace, for instance ModelC with ModelE class. Without using export, the changes would be to replace the import as well as the object created for ModelC to ModelE.</p><pre>...<br>import &#39;../model/model_c.dart&#39;; // -&gt; &#39;../model/model_e.dart&#39;; to be replaced<br>...<br><br>class UserRepo {<br><br>  ...<br>  final ModelC c = ModelC(); // -&gt; ModelE c = ModelE(); to be replaced<br>  ...<br>}</pre><p>This is fine as long as it is one or two classes but if it is used in hundreds of classes then it could be a tedious task. So can we make it easier with export keyword.</p><p>First we’ll use barrel class to import it as above.</p><pre>import &#39;../model/models_barrel.dart&#39;;<br><br>class UserRepo {<br>  ...<br>  final ModelC c = ModelC();<br>  ...<br>}</pre><p>Now, we’ve two ways to do it</p><ol><li>add <strong><em>model_e.dart</em></strong> into the barrel file as follows</li></ol><pre>file: models_barrel.dart<br><br>...<br>export &#39;model_e.dart&#39;;<br>...</pre><p>2. export the <strong><em>mode_e.dart</em></strong> class from <strong><em>model_c.dart</em></strong> as follows</p><pre>export &#39;model_e.dart&#39;;<br><br>class ModelC {}</pre><p>This way, the import won’t be affected and we can simply replace the Class name everywhere. But second way of doing it would be better because the replacement is with with ModelC and keeping ModelE is there would make more sense.</p><h3>Use case 3: Class visibility</h3><p>Let’s suppose we’ve few classes in a single class as follows</p><pre>file: model_a.dart<br><br>class ModelA {}<br>class ModelA1 {}<br>class ModelA2 {}<br>class ModelA3 {}</pre><p>Now if we want to expose only specific classes but not all, we can again make use of export keyword as follows</p><pre>export &#39;model_a.dart&#39; show ModelA1, ModelA3;</pre><p>Or we can even hide them as follows</p><pre>export &#39;model_a.dart&#39; hide ModelA1, ModelA3;</pre><h3>Use case 4: Creating barriers</h3><p>Another use case would be if we’ve a library/sdk and we want to expose limited APIs to outer world then we can again use export keyword there in similar fashion as we did above. This would be very helpful in maintaining restriction on the usage and keep things clean.</p><h3>Conclusion</h3><p>Export keyword is very useful and should be used in scaled projects. It helps keeping code clean and putting boundaries.</p><h3>That is all for now! Stay tuned!</h3><p>Connect with me (if the content is helpful to you ) on</p><ul><li><a href="https://saurabhpant.medium.com/">Medium</a></li><li><a href="https://github.com/aqua30">GitHub</a></li><li><a href="https://twitter.com/saurabh30pant">Twitter</a></li><li><a href="https://www.linkedin.com/in/saurabh-pant-44619057/">LinkedIn</a></li><li><a href="https://www.youtube.com/@_zaqua">Youtube</a></li></ul><p>Until next time…</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98d60f883190" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/import-using-export-in-flutter-98d60f883190">Import using Export in Flutter</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keys in Flutter]]></title>
            <link>https://medium.com/flutter-community/keys-in-flutter-d8f388e4655a?source=rss-2d75d9ffef06------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8f388e4655a</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Saurabh Pant]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 10:36:56 GMT</pubDate>
            <atom:updated>2024-10-17T16:49:10.893Z</atom:updated>
            <content:encoded><![CDATA[<h4>Flutter Tutorial</h4><p>In Flutter, we’ve Keys associated with every widget we use and they’re optional. In this article, we’ll explore what do they do or why they exists? In which scenarios it makes more sense to use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lqd3HkkDgrBvTiU3wU0Hg.png" /></figure><h3>What does Keys do?</h3><p>Keys are used to identify a specific widget based on a specific value in a Widget tree. By identifying a widget, we can perform specific operations on it. For instance, this can help in managing the state of a widget while the Widget may be reordered in the Widget tree.</p><p>Another example would be that the Widget is placed on multiple screens while maintaining the same state. Element tree takes its Key reference from the Widget tree to maintain the state of the Widget before rendering it on the screen.</p><p>This way the use cases becomes limited for Keys. In general cases, we might even don’t require Keys.</p><p>So far so cool!</p><h3>An Use case for Keys</h3><p>Consider a scenario where we’ve a screen with a Screen Counter Text shown at the top and we’ve two widgets of same type <strong>MyWidget</strong>.</p><p>On clicking on either of the widget A or B, it adds up and increments the Screen Counter Text on the screen and also increments their own counter which is part of each widget itself as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4sA9fZwjnYlt2e4yY1GN8w.png" /></figure><p>Next, every time we tap on either of the widget A or B, if the screen counter is even then we show Widget A on top otherwise Widget B. This way we’re reordering them every time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yztkmTQ47JCDGHoDge3L8w.png" /></figure><p>In this case, we’re dealing with multiple states.</p><ul><li>State of Screen Counter Text</li><li>State of individual tap counters on the Widget A and B</li><li>Widgets reordering</li></ul><h3>Quick view of demo code</h3><p>Consider the following code for our <strong>MyWidget</strong>.</p><pre>class MyWidget extends StatefulWidget {<br>  const MyWidget({<br>    super.key,<br>    required this.onChange,<br>    required this.title,<br>  });<br><br>  final Function(int) onChange;<br>  final String title;<br><br>  @override<br>  State&lt;StatefulWidget&gt; createState() =&gt; _MyWidget();<br>}<br><br>// Simple straight<br>class _MyWidget extends State&lt;MyWidget&gt; {<br>  int counter = 0;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      children: [<br>        Text(<br>          &#39;$counter&#39;,<br>          style: const TextStyle(<br>            fontSize: 20,<br>            color: Colors.black45,<br>          ),<br>        ),<br>        ElevatedButton(<br>          onPressed: () {<br>            setState(() {<br>              counter++;<br>            });<br>            widget.onChange(counter);<br>          },<br>          child: Text(<br>            widget.title,<br>            style: const TextStyle(<br>              fontSize: 20,<br>              color: Colors.black,<br>            ),<br>          ),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><p>Now our main screen looks like as follows</p><pre>class _MyWidget extends State&lt;SampleWidget&gt; {<br>  int screenCounter = 0;      // Screen Text Counter<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      mainAxisAlignment: MainAxisAlignment.center,<br>      children: [<br>        Text(<br>          &#39;$screenCounter&#39;,<br>          style: const TextStyle(<br>            fontSize: 40,<br>            color: Colors.red,<br>          ),<br>        ),<br>        const SizedBox(<br>          height: 20,<br>        ),<br>        _createWidget(    // Widget A<br>          counter.isEven,<br>        ),<br>        _createWidget(    // Widget B<br>          counter.isOdd,<br>        ),<br>      ],<br>    );<br>  }<br><br>  Widget _createWidget(bool status) {<br>      return MyWidget(<br>        title: status ? &#39;Widget A&#39; : &#39;Widget B&#39;,<br>        onChange: (value) {<br>          setState(() {<br>            screenCounter++;<br>          });<br>        },<br>      );<br>    }<br>}</pre><h3>How Keys help!</h3><p>If we run our app, this is how our output would look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*IkJy0ayK7bzqqinitcFvPg.gif" /><figcaption>Incorrect output</figcaption></figure><p>We can see that the reordering is correctly working, screen text counter is also correctly updating but the individual counter texts are not updating correctly. Why this is happening?</p><p>To understand this follow the below image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*y_B3_cAu09FbzBGBS_9Skg.png" /></figure><p>Here when the element tree is trying to map the elements A and B of widget A and B from Widget tree, at the initial stage, it finds them and place them correctly.</p><p>But when we reordered the widgets on the widget tree, element tree tries to check if the same element type is there or not and it finds the same type. So it doesn’t reorder the elements but updates them with the latest state from corresponding widgets from Widget tree as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VEMgPrxF2ngROJDR7O2RGA.png" /></figure><p>So when this happens, the counter states of each Widget A and B remain at the same position and it seems incorrect. So how can this be fixed?</p><p>Well! Here comes Keys into the picture. We simply update our Widgets A and B while creating them, by assigning them a Key as shown.</p><pre>Widget _createWidget(bool status) {<br>  return MyWidget(<br>    // ----- Addition ----<br>    key: ValueKey(status ? &#39;A&#39; : &#39;B&#39;),    // Adding KEY<br>    // -------------------<br>    title: status ? &#39;Widget A&#39; : &#39;Widget B&#39;,<br>    onChange: (value) {<br>      setState(() {<br>        counter++;<br>      });<br>    },<br>  );<br>}</pre><p>Now if we run the app, it’ll work as expected and shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*bW_ivJIDJQ4r1LjfY2G78w.gif" /><figcaption>Expected output</figcaption></figure><p>So what exactly changed behind the scenes?</p><p>The basic funda still remains the same for the Widget and Element trees. But now as we’ve provided unique keys to each widget, the Element tree will also check for the Key along with the Type as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ont-0AZIpskGAxT13B14Q.png" /></figure><p>Finally, our widgets are reordered correctly with their individual states.</p><h3>Types Of Keys</h3><h4><strong>Global Key</strong></h4><p>This key is used when we’ve a widget that is shared across screens and we want to maintain the same state for it.</p><p>For example, a switch for light and dark theme. No matter from which screen we changed it, it should remain in the same state.</p><p>Another instance could be that we want to find out the position of a widget in the scroll view.</p><p>In such cases, we can use Global key.</p><h4>Value Key</h4><p>This key is used when we want to identify widgets locally based on a value. The scope is limited to a parent widget.</p><h4>Object Key</h4><p>This key is used when we want to identify widgets and the uniqueness is defined by a combination of different values. In such cases, we use Object key where we pass a complete object as a key identifier.</p><h4>Unique Key</h4><p>This key is used when we don’t have any exact criteria for uniqueness for a widget but it can still be unique.</p><h3>Conclusion</h3><p>Keys are useful in scenarios where we’re altering the ordering of widgets or some widget needs to maintain its state across screens. Keys are also handy in state management for widgets.</p><h3>That is all for now! Stay tuned!</h3><p>Connect with me (if the content is helpful to you ) on</p><ul><li><a href="https://saurabhpant.medium.com/">Medium</a></li><li><a href="https://github.com/aqua30">GitHub</a></li><li><a href="https://twitter.com/saurabh30pant">Twitter</a></li><li><a href="https://www.linkedin.com/in/saurabh-pant-44619057/">LinkedIn</a></li><li><a href="https://www.youtube.com/@_zaqua">Youtube</a></li></ul><p>Until next time…</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8f388e4655a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/keys-in-flutter-d8f388e4655a">Keys in Flutter</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Futures, async & await in Flutter— Simplified]]></title>
            <link>https://blog.devgenius.io/futures-async-await-in-flutter-simplified-690ed76ce7fa?source=rss-2d75d9ffef06------2</link>
            <guid isPermaLink="false">https://medium.com/p/690ed76ce7fa</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Saurabh Pant]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 14:36:11 GMT</pubDate>
            <atom:updated>2024-08-06T03:24:16.577Z</atom:updated>
            <content:encoded><![CDATA[<h4>Flutter Tutorial</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YhYJs_jC80N5m6C7zDF-Dg.png" /></figure><p>Flutter applications are single threaded. There are various techniques in Flutter via which we can achieve asynchronous functionality and related behaviour but in this article I’ll share my understanding on</p><ul><li>what it means to have a Future?</li><li>does marking a function as async actually process it in background?</li><li>why we use await?</li></ul><h3>What it means to have a Future?</h3><p>Future is something that will happen in some point in time and will return a value. It is neither happening at the current moment nor it is blocking next operations to proceed. For example, we attempt an exam but we get the result after some time in future and when the result is declared, we get a value in terms of either we cleared or failed it.</p><p>In Flutter, a simple future looks like as follows</p><pre>Future(() =&gt; print(&#39;a future&#39;));  // prints on console</pre><p>The above future means that there will be a print statement on console in some time.</p><pre>Future&lt;int&gt;(() =&gt; 1);  // returns 1</pre><p>The above future means that it’ll return an integer value in some time and not immediately.</p><p>Let’s take another type of future as follows</p><pre>// prints on console after 500 ms<br>Future.delayed(const Duration(milliseconds: 500), () =&gt; print(&#39;delayed a&#39;));<br><br>// returns 1 after 500ms<br>Future.delayed(const Duration(milliseconds: 500), () =&gt; 1);</pre><p>In the above, the first future states that there will be a print statement on console after 500ms and second future will return an integer after 500 ms.</p><h4>How an operation takes place in Future?</h4><p>Well! If we look at the Future’s internal working, we’ll find that a future either takes a function or a value as input and it runs a timer. Once the duration is over, it returns a result as follows</p><pre>// Actual code from Future.delayed constructor<br>_Future&lt;T&gt; result = new _Future&lt;T&gt;();<br>new Timer(duration, () {<br>  if (computation == null) {<br>    result._complete(null as T);<br>  } else {<br>    try {<br>      result._complete(computation());<br>    } catch (e, s) {<br>      _completeWithErrorCallback(result, e, s);<br>    }<br>  }<br>});<br>return result;</pre><ul><li>If we’ve provided a duration then the timer will run for that particular duration and then later it executes the function or returns the value.</li></ul><pre>Future.delayed(const Duration(milliseconds: 500), () =&gt; 1);</pre><ul><li>If we’ve not provided any duration then the duration is zero and the callback is executed as soon as the timer starts.</li></ul><pre>Future(() =&gt; print(&#39;a future&#39;));  // duration is Duration.zero</pre><h4>Are there more Future constructors?</h4><p>Yes! There are other types of future constructors which are as follows</p><pre>// microtask have higher priority than similar futures<br>Future.microtask(() =&gt; 1);<br><br>// value future returns a value immediately<br>Future.value(1);<br>Future.value(() =&gt; 1);<br><br>// sync future returns a value synchronously<br>Future.sync(() =&gt; 1);<br><br>// error future returns error<br>Future.error(&#39;&#39;);<br><br>// wait future can wait for multiple future executions<br>Future.wait([Future(() =&gt; 1), Future.value(1)]);</pre><h4>What else do we need?</h4><p>So far we saw how Futures operating. But now the question arises how to use the result of a Future in the present i.e in the synchronously or on the main thread? Let’s consider an example</p><pre>void main() {<br>  print(&#39;main&#39;);<br>  late int x;<br>  Future&lt;int&gt;(() =&gt; 1).then((value) =&gt; x = value);<br>  print(x);<br>  print(&#39;end&#39;);<br>}</pre><p>In the above scenario, we initialises x with the returned value from the future and try to print it. But if we run this, we get the following output</p><pre>Unhandled exception:<br>LateInitializationError: Local &#39;x&#39; has not been initialized.</pre><p>It says x is not initialised! But why? Because by the time our future returns, we already tried printing the x value which is not initialised by then &amp; hence exception.</p><p>So what can we do? How can we make it work for us?</p><h3>async/await in Action</h3><h4>async</h4><p>Flutter provides us a keyword called <strong><em>async</em></strong>. We can mark any function as async as follows</p><pre>void main() async { ... }</pre><p>This async keyword makes a function to execute concurrently with other instructions and not in parallel. This way we can suspend some execution and can resume once that execution is completed while not blocking the main code execution. Consider the following example</p><pre>void main() {<br>  print(&#39;main&#39;);<br>  a();  // async<br>  b();  // async<br>  c();  // sync<br>  print(&#39;end&#39;);<br>}<br><br>void a() async {<br>  Future(() =&gt; print(1));<br>  print(&#39;a&#39;);<br>}<br><br>void b() async {<br>  Future.delayed(const Duration(milliseconds: 500)).then((value) =&gt; print(&#39;2&#39;));<br>  print(&#39;b&#39;);<br>}<br><br>void c() {<br>  print(&#39;c&#39;);<br>}</pre><p>Below is the execution order for the above code. Here we can see that both the futures with 1 and 2 will be processed in the end and rest of the prints are in the same order as defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9RHego_XkkythOuaHkNdg.png" /></figure><p>What if we want to wait for the 1 and 2 futures and then executes their corresponding functions? Here comes the <strong><em>await</em></strong> keyword in picture.</p><h4>await</h4><p>If we want to wait for a future to complete its execution then we can use await keyword as follows</p><pre>await Future(() =&gt; print(1));</pre><p>This holds the execution until the future returned. Now checkout if I only add wait for the future 1 in the above example, the execution order changes significantly as shown</p><pre>void a() async {<br>  await Future(() =&gt; print(1));<br>  print(&#39;a&#39;);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZ0lgnzpDMXrcDf7Rdop8w.png" /></figure><h4>Return value from async</h4><p>To return a value from async, we can wrap the resulting data type in future as follows</p><pre>Future&lt;int&gt; a() async { ... }</pre><p>To access the returned value of the future, we do as follows</p><pre>final a = await Future(() =&gt; 1);</pre><h4>Intricacies of a normal &amp; async function</h4><p><strong>I:</strong><br>An async function without waiting for any future to complete its work inside it, executes synchronously and can be equivalent to a normal function.</p><pre>// Normal function or without async<br>a() {  <br>  Future(() =&gt; print(1));<br>  print(&#39;a&#39;);<br>}<br><br>// Async function<br>a() async {  <br>  Future(() =&gt; print(1));<br>  print(&#39;a&#39;);<br>}</pre><p>Both the above functions behaves exactly same. Because neither of them is dependent on any asynchronous task. They just starts a future and forgets it. Hence marking it async or not doesn’t matter here.</p><p><strong>II:</strong></p><pre>// Normal function or without async<br>a() {  <br>  Future(() =&gt; print(1));  // error<br>  print(&#39;a&#39;);<br>}<br><br>// Async function<br>a() async {  <br>  await Future(() =&gt; print(1));<br>  print(&#39;a&#39;);<br>}</pre><p>This time they are not equivalent and behaves differently. Async ‘a’ function waits for the future where as the normal one doesn’t.</p><p>Also, if we try to add await without async keyword, we’ll get a compile time error. Because await can’t be used on main thread. It has to be in a concurrent part of the thread.</p><p><strong>III:</strong></p><p>Marking a function async don’t have any significant effect until it waits for a future task to complete. Otherwise, async function executes almost synchronously.</p><pre>print(&#39;main&#39;);<br>  a();  // async<br>  b();  // async<br>  c();  // sync<br>  print(&#39;end&#39;);</pre><p>We can see in this execution that though a is an async function but because it is not dependent on any future task, its print statement is logged before b and c.</p><p><strong>IV:</strong></p><p>async doesn’t start a new thread instead it make the code to run concurrently with the main code. It still remain a part of the main thread or isolate. To execute some heavy task in parallel, we need to use Isolates.</p><h3>Conclusion</h3><p>Though these are very wide topics but I’ve tried simplifying the understanding for each of them. This much information is a good to start on async programming in Flutter.</p><p>I hope you find this informative and useful. Please do try to play around these keywords and you’ll be definitely be amazed.</p><h3>That is all for now! Stay tuned!</h3><p>Connect with me (if the content is helpful to you ) on</p><ul><li><a href="https://saurabhpant.medium.com/">Medium</a></li><li><a href="https://github.com/aqua30">GitHub</a></li><li><a href="https://twitter.com/saurabh30pant">Twitter</a></li><li><a href="https://www.linkedin.com/in/saurabh-pant-44619057/">LinkedIn</a></li></ul><p>Until next time…</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=690ed76ce7fa" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/futures-async-await-in-flutter-simplified-690ed76ce7fa">Futures, async &amp; await in Flutter— Simplified</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[abstraction & interface in Flutter — A Thought]]></title>
            <link>https://blog.devgenius.io/abstraction-interface-in-flutter-a-thought-8e2e0fd95540?source=rss-2d75d9ffef06------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e2e0fd95540</guid>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[abstraction]]></category>
            <dc:creator><![CDATA[Saurabh Pant]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 16:26:25 GMT</pubDate>
            <atom:updated>2024-08-01T16:56:08.443Z</atom:updated>
            <content:encoded><![CDATA[<h4>Flutter Tutorial</h4><h3>abstraction &amp; interface in Flutter — A Thought</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9zaUy_gGiYKE6_XKdDeIg.png" /></figure><p>In Flutter, if we want a class to be unaccessible outside of the library, or to prevent any other class from inheriting it, or to prevent its direct initiation , there are class modifiers that we can use to set such restrictions on a class usage. Following are the modifiers available in Flutter</p><ul><li>abstract</li><li>base</li><li>final</li><li>interface</li><li>sealed</li><li><a href="https://dart.dev/language/mixins#class-mixin-or-mixin-class">mixin</a></li></ul><p>But in this article, I’ll focus on abstract and interface keywords usage both as a concept and implementation in Flutter.</p><h3>abstraction as a Concept</h3><p>By abstraction what I understand is that it is a practice of wrapping functions and variables of a certain functionality/feature within an object (say <strong><em>AbsObj</em></strong>) such that this functionality/feature can only be accessed by inheriting from <strong><em>AbsObj </em></strong>but not via <strong><em>AbsObj instance.</em></strong></p><p>This prevents duplication of same functionality across application and keeps it same for its inheriting children.</p><h4>abstraction as implementation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDpwt3UQIedr3GK4BVVSgA.png" /></figure><p>In the above example, we’ve a button and it has a text styling function, a shape defining function and a dimension function. Now if want the button functionality, we can use this Button wrapper as a base and can create new types of buttons over it like Round corner and Circular button.</p><p>This gives us an advantage of keeping all the buttons following a common pattern and in technical terms they can also become of same type. This approach can be applied in design-system module of the application.</p><p>Let see the above example in code terms. We first create our button class as follows</p><pre>abstract class Button extends StatelessWidget {<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Container(<br>      width: dimension.width,<br>      height:dimension.height,<br>      decoration: decoration(),<br>      child: Text(<br>         displayText,<br>         style: textStyle(),<br>      ),<br>    ); <br>  }<br><br>  TextStyle textStyle();<br><br>  Decoration decoration();<br><br>  Dimension dimension();<br>}</pre><p>We use abstract class modifier to prevent its direct initiation. Now we create our Round corner button class as follows</p><pre>//....<br>class RoundCornerButton extends Button {<br>  @override<br>  Dimension dimension() {<br>    return Dimension(width: 200, height: 50);<br>  }<br><br>  @override<br>  Decoration shape() {<br>    return const BoxDecoration(<br>      shape: BoxShape.rectangle,<br>      borderRadius: BorderRadius.all(Radius.circular(16))<br>    );<br>  }<br><br>  @override<br>  TextStyle textStyle() {<br>    return const TextStyle(<br>      fontSize: 18,<br>      color: Colors.black<br>    );<br>  }<br><br>}</pre><p>and circular button class as follows.</p><pre>//....<br>class CircularButton extends Button {<br>  @override<br>  Dimension dimension() {<br>    return Dimension(width: 100, height: 100);<br>  }<br><br>  @override<br>  Decoration shape() {<br>    return const BoxDecoration(<br>      shape: BoxShape.circle,<br>    );<br>  }<br><br>  @override<br>  TextStyle textStyle() {<br>    return const TextStyle(<br>      fontSize: 12,<br>      color: Colors.orangeAccent<br>    );<br>  }<br><br>}</pre><p>As we can see above that we overridden the three functions required to create a button and that’s it. We customised the parameters and a new type of button is created. But the button creation part is hidden from us. In other words button creation is abstracted from us. This is <strong><em>abstraction</em></strong>.</p><p>Though this is a very simple example but it conveys the intention.</p><h3>interface as a Concept</h3><p>Interface works as contract or connector between two sections. It exposes certain end points for the accessor. We can link polymorphism to it such that same interface may appear with different implementation to two different parts in the application.</p><h4>interface as implementation</h4><p>Consider the example with following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNnMAuJpeFTyyilWb3nz9A.png" /></figure><p>We have created our DataSource as an interface. RemoteDataSource and MockDataSource becomes its implementations.</p><pre>interface class DataSource {<br>   <br>  List&lt;UserPosts&gt; userPosts() {}<br>  LoginData userLogin() {}  <br>  Response userLogout() {}<br>}<br><br>class RemoteDataSource implements DataSource { ... }<br>class MockDataSource implements DataSource { ... }</pre><p>Now when we connect this data source to lets say a repository then the repository can make use either of the implementation as per its need.</p><pre>class UserRepositoryImpl implements UserRepository {<br><br>  // data source implementation selected as Remote<br>  final DataSource dataSource = RemoteDataSource();<br>  // data source implementation selected as Mock<br>  // final DataSource dataSource = MockDataSource();<br><br>  @override<br>  Future&lt;List&lt;UserPosts&gt;&gt; userPosts() async {}<br><br>  @override<br>  Future&lt;LoginData&gt; userLogin() async {}<br><br>  @override<br>  Future&lt;Response&gt; userLogout() async {}<br>}</pre><p>If we’re building a library or sdk, we often allow others to provide their own implementation of the interface the library/sdk offers.</p><p>This is also helpful if we’re having multiple builds/flavours of our app and each type require a different implementation of the same interface.</p><h3>abstract interface in Flutter</h3><p>In flutter, abstract and interface independently works as we discussed above and technical differences are there in their implementations.</p><pre>abstract interface class DataSource {<br>   <br>  List&lt;UserPosts&gt; userPosts();<br>  LoginData userLogin();<br>  Response userLogout();<br>}</pre><p>We use such implementation when we want to create an interface but don’t want to provide the functions body, abstract keyword helps in that. Also this prevents other classes to extend this class.</p><p>If we only mark a class as interface then we need to provide the functions body.</p><h3>Conclusion</h3><p>While abstraction helps us in generalise common functionality and hide it from other layers, interface connects us with other part of the application by exposing some common end points.</p><p><strong><em>abstract &amp; interface </em></strong>keywords are a powerful way to make your code more robust. Both the modifiers has its own usage but they can be clubbed together to suit your needs. Try it and you’ll be good!</p><h3>That is all for now! Stay tuned!</h3><p>Connect with me (if the content is helpful to you ) on</p><ul><li><a href="https://saurabhpant.medium.com/">Medium</a></li><li><a href="https://github.com/aqua30">GitHub</a></li><li><a href="https://twitter.com/saurabh30pant">Twitter</a></li><li><a href="https://www.linkedin.com/in/saurabh-pant-44619057/">LinkedIn</a></li></ul><p>Until next time…</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e2e0fd95540" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/abstraction-interface-in-flutter-a-thought-8e2e0fd95540">abstraction &amp; interface in Flutter — A Thought</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[setState in Flutter — Exposed!]]></title>
            <link>https://blog.devgenius.io/setstate-in-flutter-exposed-eaf32651c2a9?source=rss-2d75d9ffef06------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaf32651c2a9</guid>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Saurabh Pant]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 15:22:03 GMT</pubDate>
            <atom:updated>2024-07-23T16:42:27.323Z</atom:updated>
            <content:encoded><![CDATA[<h4>Flutter Tutorial</h4><h3><em>setState</em> in Flutter — Exposed!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7O1LxAbwH54BtshTkr4dIQ.png" /></figure><p>We all know that setState function is used for rebuilding our widget tree whenever there is a change in the internal state of the widget. And it is very straightforward to use it. But have you ever noticed the below two scenarios</p><pre>// Scenario 1<br>setState(() {<br>  currentPage++;<br>});<br><br>// Scenario 2<br>currentPage++;<br>setState(() {});</pre><p>Both works exactly the same. Increments the page and refreshes the UI.</p><p>But then why we have a callback in the setState function? What does it do and how setState is working behind the scenes? I was asked this question and I didn’t know it at then so tried looking for answers and would like to share what I understood.</p><h3>setState use case</h3><p>The definition of the setState function is</p><pre>void setState(VoidCallback fn) { }</pre><p>It takes a void callback and it calls it immediately and synchronously. So if we want to refresh the UI but don’t call the setState function, there will be no change anywhere.</p><h3>What happens when setState is called</h3><p>The setState function tells the Flutter framework that the internal state of the widget is changed and can be refreshed. Ok! But how it actually notifies the framework? Read on..</p><pre>@protected<br>void setState(VoidCallback fn) {<br>  // ...<br>  if (_debugLifecycleState == _StateLifecycle.defunct) {<br>      throw FlutterError.fromParts(&lt;DiagnosticsNode&gt;[<br>        ErrorSummary(&#39;setState() called after dispose(): $this&#39;),<br>        ErrorDescription(<br>          &#39;This error happens if you call setState() on a State object for a widget that &#39;<br>          &#39;no longer appears in the widget tree (e.g., whose parent widget no longer &#39;<br>          &#39;includes the widget in its build). This error can occur when code calls &#39;<br>          &#39;setState() from a timer or an animation callback.&#39;,<br>        ),<br>        ErrorHint(<br>          &#39;The preferred solution is &#39;<br>          &#39;to cancel the timer or stop listening to the animation in the dispose() &#39;<br>          &#39;callback. Another solution is to check the &quot;mounted&quot; property of this &#39;<br>          &#39;object before calling setState() to ensure the object is still in the &#39;<br>          &#39;tree.&#39;,<br>        ),<br>        ErrorHint(<br>          &#39;This error might indicate a memory leak if setState() is being called &#39;<br>          &#39;because another object is retaining a reference to this State object &#39;<br>          &#39;after it has been removed from the tree. To avoid memory leaks, &#39;<br>          &#39;consider breaking the reference to this object during dispose().&#39;,<br>        ),<br>      ]);<br>    }<br>    if (_debugLifecycleState == _StateLifecycle.created &amp;&amp; !mounted) {<br>      throw FlutterError.fromParts(&lt;DiagnosticsNode&gt;[<br>        ErrorSummary(&#39;setState() called in constructor: $this&#39;),<br>        ErrorHint(<br>          &#39;This happens when you call setState() on a State object for a widget that &#39;<br>          &quot;hasn&#39;t been inserted into the widget tree yet. It is not necessary to call &quot;<br>          &#39;setState() in the constructor, since the state is already assumed to be dirty &#39;<br>          &#39;when it is initially created.&#39;,<br>        ),<br>      ]);<br>    }<br><br>  final Object? result = fn() as dynamic;<br>  assert(() {<br>    if (result is Future) {<br>      throw FlutterError.fromParts(&lt;DiagnosticsNode&gt;[<br>        ErrorSummary(&#39;setState() callback argument returned a Future.&#39;),<br>        ErrorDescription(<br>          &#39;The setState() method on $this was called with a closure or method that &#39;<br>              &#39;returned a Future. Maybe it is marked as &quot;async&quot;.&#39;,<br>        ),<br>        ErrorHint(<br>          &#39;Instead of performing asynchronous work inside a call to setState(), first &#39;<br>              &#39;execute the work (without updating the widget state), and then synchronously &#39;<br>              &#39;update the state inside a call to setState().&#39;,<br>        ),<br>      ]);<br>    }<br>    return true;<br>  }());<br>  _element!.markNeedsBuild();<br>}</pre><blockquote>Above code snippet is taken from official setState documentation.<br><a href="https://api.flutter.dev/flutter/widgets/State/setState.html">https://api.flutter.dev/flutter/widgets/State/setState.html</a></blockquote><p>Once we call the setState, internally it does some sanity checks like</p><ul><li>the widget is mounted or not</li><li>dispose call is made or not</li></ul><p>If neither of the above is true then it executes our callback and then it calls the <strong><em>markNeedsBuild()</em></strong> function. That is it. This is the only execution setState function does.</p><p>Now what is this new function <strong><em>markNeedsBuild</em></strong>? Let’s check it.</p><h4>markNeedsBuild</h4><p>Earlier, <strong><em>markNeedsBuild</em></strong> function was used. It didn’t have any callback. It marks the element as dirty (i.e its state is updated and ready to be rebuilt) and add it to the list of widgets to be rebuilt in next frame.</p><h4>markNeedsBuild drawback</h4><p>Developers were not sure when the update made on the state would refresh the UI, so they used to call <strong><em>markNeedsBuild</em></strong> function more than necessary.</p><p>If we call <strong><em>markNeedsBuild </em></strong>multiple times in one frame then it would build same element multiple times which is inefficient. We needed a way to mark the element as dirty once per frame so that it can be built only once per frame.</p><p>Hence, a callback is added and setState was formed.</p><p>But how does this improved the performance?</p><h4>Performance aspect</h4><p><strong><em>setState</em></strong> function is idempotent which means that the output won’t change even if you call it repeatedly in a frame and when state is changed only once. So calling setState directly has no performance cost as such.</p><p>But it does have a cost associated with it due to widget rebuilds. So it is advised to be called only when state is updated meaningfully.</p><h4>So what’s the difference?</h4><pre>// Scenario 1<br>setState(() {<br>  currentPage++;<br>});<br><br>// Scenario 2<br>currentPage++;<br>setState(() {});</pre><p>There is no difference. We saw that calling setState tells the Flutter framework to rebuild the UI and that is why both of the above scenarios works same.</p><p>But it is advised to</p><ul><li>update the state within the callback so that developers know what is exactly updated</li><li>in case of listeners or animation controllers, if the setState is called, there should be a comment added in its callback that animation state is being updated</li><li>not perform any computational part in this callback as it would only delay the UI updates</li></ul><h3>Conclusion</h3><p><strong><em>setState</em></strong> callback is there for developers to carefully make the UI updates and make the state changes in the callback to know what is updated and when. Behaviour wise, our scenarios works same.</p><h3>That is all for now! Stay tuned!</h3><p>Connect with me (if the content is helpful to you ) on</p><ul><li><a href="https://saurabhpant.medium.com/">Medium</a></li><li><a href="https://github.com/aqua30">GitHub</a></li><li><a href="https://twitter.com/saurabh30pant">Twitter</a></li><li><a href="https://www.linkedin.com/in/saurabh-pant-44619057/">LinkedIn</a></li></ul><p>Until next time…</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaf32651c2a9" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/setstate-in-flutter-exposed-eaf32651c2a9">setState in Flutter — Exposed!</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[const, final and static in Flutter | What & Why]]></title>
            <link>https://blog.devgenius.io/const-final-and-static-in-flutter-what-why-d6e4b3cd1d1f?source=rss-2d75d9ffef06------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e4b3cd1d1f</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Saurabh Pant]]></dc:creator>
            <pubDate>Thu, 18 Jul 2024 12:03:15 GMT</pubDate>
            <atom:updated>2024-07-20T17:48:39.450Z</atom:updated>
            <content:encoded><![CDATA[<h4>Flutter Tutorial</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lw5VIBcawuKa0psARqb1aw.png" /></figure><p>Recently I was asked a basic question about why we have two separate keywords const and final in Flutter when both are there, doing the same job for us and what does the static keyword does?</p><p>At that point in time, I was also got confused but decided to clear it in my mind and share the details with everyone. So let’s see what I understood.</p><h3>const Keyword</h3><p>In Flutter, when we want to define a variable whose value is not going to change then we prefer declaring it as a const variable as follows</p><pre>const int x = 1;</pre><p>A const variable is defined at the time of its initialisation so we can call it as compile time constants too. Also if we’ll try to modify its value, we’ll get an error immediately and we won’t be able to create our build or run the code.</p><p>Now, this const variable is not declared in context of any class and hence we can access them anywhere in our application. So const variables are declared at application level.</p><h3>final Keyword</h3><p><em>final</em> keyword, on the other hand behaves same as const variables but with one differentiation as that they can be assigned a value once.</p><p>What does it mean?</p><p>Well! It means unlike const variables, final variables are not given any value during their initialisation at compile time but rather at run time. But how’s that?</p><pre>class GalleryCard extends StatelessWidget {<br>  final String image;<br>  final int index;<br>  final double screenWidth;<br>  final double scrollOffset;<br><br>  const GalleryCard(<br>      {super.key,<br>      required this.image,<br>      required this.index,<br>      required this.screenWidth,<br>      required this.scrollOffset});<br>  //...<br>}</pre><p>For instance, the above class constructor is created with final variables which are given values at run time when this constructor is called, they are initialised and they now become const for us. Hence they’re also called as Run time constants. final varibales can also be declared outside of a class as follows</p><pre>final x = [];  // array is not a constant value so can be final</pre><p>In fact, const variables are implicitly final variables 😄.</p><h3>Difference in const and final</h3><p>So the question is what’s the difference?</p><p>Well! One answer to this question is as stated in the definition that const are compile time constants and final are run time.</p><p>The other difference is that memory wise if we look at them, const variables are allocated fixed memory as soon as they’re initialised whereas final variables comes into the memory only after the initialisation. Until initialisation, final variables are not present in memory. That is why it is advised to use const variables carefully and not overuse them, otherwise they’ll consume more memory.</p><p>Another difference is that you can easily make final variables a class member but const variables can’t be treated as a class member.</p><p>But then what if we want to access a const variable from a within a class?</p><h3>static Keyword</h3><p>Here comes the <em>static</em> keyword. <em>static</em> keyword is used to declare a const variable within a class as</p><pre>class A {<br>  static const int x = 0;<br>}</pre><p>Now we can access the const variable x from class A but without creating an instance of class A. So static keyword make a variable or function accessible without creating instance of the class.</p><p>Hope this would be informative to you.</p><h3>That is all for now! Stay tuned!</h3><p>Connect with me (if the content is helpful to you ) on</p><ul><li><a href="https://saurabhpant.medium.com/">Medium</a></li><li><a href="https://github.com/aqua30">GitHub</a></li><li><a href="https://twitter.com/saurabh30pant">Twitter</a></li><li><a href="https://www.linkedin.com/in/saurabh-pant-44619057/">LinkedIn</a></li></ul><p>Until next time…</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6e4b3cd1d1f" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/const-final-and-static-in-flutter-what-why-d6e4b3cd1d1f">const, final and static in Flutter | What &amp; Why</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallax Gallery View Animation in Flutter]]></title>
            <link>https://blog.devgenius.io/parallax-gallery-view-animation-in-flutter-e55a267fd5c8?source=rss-2d75d9ffef06------2</link>
            <guid isPermaLink="false">https://medium.com/p/e55a267fd5c8</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[parallax]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Saurabh Pant]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 17:59:25 GMT</pubDate>
            <atom:updated>2024-06-18T19:31:55.965Z</atom:updated>
            <content:encoded><![CDATA[<h4>Flutter Tutorial</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UHag3B3Dop10Kh2ce7pOSQ.png" /></figure><p>Recently, while I was viewing google photos, the memory carousel at the of the page got my attention. It was moving horizontally with a nice parallax animation from both left and right end. I really liked it and decided to give it a try in Flutter and the final result looks like as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*80yKL-U2jFUTBdqv_2H9Ww.gif" /></figure><p>In the beginning it looked slightly tough to build but I managed to get through and let’s see how it was built.</p><h3>The Conceptual part</h3><p>Let’s see what are the details in this animation so as to use them in our implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*aU7N-JNNanWTY38lS0Gqfg.png" /></figure><ul><li>there are 2 complete images along with either one image with 85% portion visible or two images with ~42% portion is visible at any given time</li><li>as soon as any image hits the left side of the screen or is out to the right side 15%, its parallax starts</li><li>if image is entering in the left side then the image parallax is towards right and vice versa</li><li>there is 8 px of left margin on each image which is required to be considered in the calculations</li><li>lastly, scroll offset is the key for all the calculations</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*RNQn0HRIM79WTBLF23H42g.png" /></figure><h3>The Implementation</h3><h4>Create GalleryCard</h4><p>We first create our main GalleryCard as follows</p><pre>class GalleryCard extends StatelessWidget {<br>  final String image;<br>  final int index;<br>  final double screenWidth;<br>  final double scrollOffset;<br><br>  const GalleryCard(<br>      {super.key,<br>      required this.image,<br>      required this.index,<br>      required this.screenWidth,<br>      required this.scrollOffset});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    // basic calculations<br>    final itemWidth = screenWidth / 2.85;<br>    final itemHeight = itemWidth * 1.5;<br>    return Container(<br>      width: itemWidth,<br>      height: itemHeight,<br>      clipBehavior: Clip.antiAlias,<br>      decoration: const BoxDecoration(<br>          color: Colors.red,<br>          borderRadius: BorderRadius.all(Radius.circular(24))),<br>      child: Image.asset(<br>        image,<br>        fit: BoxFit.cover,<br>        alignment: Alignment(<br>            0,<br>            0<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Now we add this card few times in a row and put that row in a horizontal scrollview as follows</p><pre>@override<br>Widget build(BuildContext context) {<br>  final width = MediaQuery.of(context).size.width;<br>  return SingleChildScrollView(        // Scrollview<br>    scrollDirection: Axis.horizontal,<br>    controller: controller,<br>    child: Container(<br>      color: Colors.white,<br>      child: Row(                      // Row containing our Gallery card<br>        children: [<br>          ...List.generate(images.length, (index) {<br>            return Padding(<br>              padding: const EdgeInsets.only(left: 8.0),<br>              child: GalleryCard(<br>                screenWidth: width,<br>                scrollOffset: scrollOffset,<br>                image: images[index],<br>                index: index,<br>              ),<br>            );<br>          })<br>        ],<br>      ),<br>    ),<br>  );<br>}</pre><p>If run our code upto this step then we would get something as shown</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*i1f43J2EdUL5l_Oolh-i4A.gif" /><figcaption>No parallax</figcaption></figure><h4>Card Dimensions Calculations</h4><p>We’ll set up the left side parallax by doing the calculations as per the conceptual section as follows</p><pre>final marginOffset = 8 * (index + 1);<br>final lowerRange = (index * itemWidth) + marginOffset;<br>final highRange = ((index + 1) * itemWidth) + marginOffset;</pre><ul><li>calculating the margin offset for each card. this is the padding that we provided to each card from left. This margin is to be considered otherwise the movement for each card will not be consistent.</li><li>then we calculate the lower (left) and high (right) position of each card</li></ul><h4>Left Side Parallax</h4><p>Using the card dimensions, we can calculate few values for left side as follows</p><pre>// left side calculations<br>final isInLeftSideRange = scrollOffset &gt;= lowerRange &amp;&amp; scrollOffset &lt;= highRange;<br>final leftSideOffset = highRange - scrollOffset;<br>final leftSideDivisor = index &gt; 0 ? (lowerRange - marginOffset) / index : highRange - marginOffset;</pre><ul><li><em>isInLeftSideRange </em>: indicates if the scrolling offset lies within this card’s area. If yes then it means the card has started entering the left side of the screen.</li><li><em>leftSideOffset</em> : value which indicates how much the card has been moved into the left side</li><li><em>leftSideDivisor</em> : a denominator to calculate the percentage value for parallax</li></ul><p>Now we calculate the fraction offset which indicates the percentage of the card into the left side as follows</p><pre>final fractionOffset = (offset &lt; 0 ? 1 : leftSideOffset) / leftSideDivisor;</pre><p>Finally we can calculate the value for our parallax as follows</p><pre>final leftParallaxPercent = isInLeftSideRange ? (1 - fractionOffset) : 0.0;</pre><p>We can apply this percent into the x coordinate of the image Alignment as follows</p><pre>child: Image.asset(<br>  image,<br>  fit: BoxFit.cover,<br>  alignment: Alignment(<br>      leftParallaxPercent,<br>      0<br>  ),<br>),</pre><p>If we run our code upto this step, we would get our gallery view with only left side parallax as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*TNvHEjfLLgWltqxQXEX91g.gif" /></figure><h4>Right Side Parallax</h4><p>Similarly as we found out the left side parallax percentage, we can find out the right side one but with slight updates.</p><pre>// right side calculations<br>final rightSideScrollOffset = lowerRange - scrollOffset;<br>final rightSideOffsetThreshold = screenWidth - (itemWidth * 0.85);<br>final isInRightSideRange = rightSideScrollOffset &gt; rightSideOffsetThreshold &amp;&amp; rightSideScrollOffset &lt; screenWidth;<br>final rightSideOffset = rightSideScrollOffset - rightSideOffsetThreshold;<br>final rightSideDivisor = screenWidth - rightSideOffsetThreshold + marginOffset;</pre><ul><li>r<em>ightSideScrollOffset: </em>value indicate the amount of card scrolled into the right side of the screen</li><li><em>rightSideOffsetThreshold: </em>maximum value upto which parallax to be shown when scrolling from right to left</li><li><em>isInRightSideRange: </em>if the card has entered into the right side of the screen when scrolling from left to right</li><li><em>rightSideOffset: </em>amount by which the card is visible when scrolling from right to left</li><li><em>rightSideDivisor: </em>a denominator to calculate the percentage value for parallax</li></ul><h4>Final caluclations</h4><p>As we already have left side values, we can adjust the final calculation with both left and right side values as follows</p><pre>// final calculations<br>final offset = isInLeftSideRange ? leftSideOffset : rightSideOffset;<br>final divisor = isInLeftSideRange ? leftSideDivisor : rightSideDivisor;<br>final fractionOffset = (offset &lt; 0 ? 1 : offset) / divisor;<br>final leftParallaxPercent = isInLeftSideRange ? (1 - fractionOffset) : 0.0;<br>final rightParallaxPercent = isInRightSideRange ? fractionOffset : 1.0;<br>final leftPercent = -leftParallaxPercent;<br>final rightPercent = rightParallaxPercent;</pre><p>Replacing the above values in our image widget alignment as follows</p><pre>child: Image.asset(<br>  image,<br>  fit: BoxFit.cover,<br>  alignment: Alignment(<br>      isInLeftSideRange ? leftPercent : (isInRightSideRange ? rightPercent : 0.0),<br>      0<br>  ),<br>),</pre><p>Running our code now would give us our final result.</p><p>Bamn! We’ve successfully created our Parallax Gallery animation from both end.</p><p>Hope you’ve enjoyed it! You can watch the speed code video on YouTube</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQNe-bxZBFmg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQNe-bxZBFmg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQNe-bxZBFmg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1afae82fd93a464df90d6cf094e4dae3/href">https://medium.com/media/1afae82fd93a464df90d6cf094e4dae3/href</a></iframe><p>Or can checkout the repo below</p><p><a href="https://github.com/aqua30/parallax-gallery-animation">GitHub - aqua30/parallax-gallery-animation: Parallax Gallery Animation from both side of the screen.</a></p><p>Comment down to let me know if you have any inputs on this.</p><h3>That is all for now! Stay tuned!</h3><p>Connect with me (if the content is helpful to you ) on</p><ul><li><a href="https://saurabhpant.medium.com/">Medium</a></li><li><a href="https://github.com/aqua30">GitHub</a></li><li><a href="https://twitter.com/saurabh30pant">Twitter</a></li><li><a href="https://www.linkedin.com/in/saurabh-pant-44619057/">LinkedIn</a></li></ul><p>Until next time…</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e55a267fd5c8" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/parallax-gallery-view-animation-in-flutter-e55a267fd5c8">Parallax Gallery View Animation in Flutter</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reflect Changes in Async from Local Storage with ChangeNotifier in Flutter]]></title>
            <link>https://blog.devgenius.io/reflect-changes-in-async-from-local-storage-with-changenotifier-in-flutter-ab4ca00fbe2b?source=rss-2d75d9ffef06------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab4ca00fbe2b</guid>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[preference]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Saurabh Pant]]></dc:creator>
            <pubDate>Thu, 11 Apr 2024 18:43:26 GMT</pubDate>
            <atom:updated>2024-04-15T16:25:24.731Z</atom:updated>
            <content:encoded><![CDATA[<h4>Flutter Tutorial</h4><h4>With ChangeNotifier comes great changes!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IqqnH1I4vhyJavFFU_oJDw.png" /></figure><p>If you’re coming from the native android background then you must be familiar with Kotlin flows which are used with async computation to reflect back the changes on the UI. Even local storage solution Data Store in Android provide Flows support and I already have written an article on the same.</p><p><a href="https://proandroiddev.com/preference-layer-using-data-store-android-jetpack-f47416ea80e2">Preference Layer using Data Store- Android Jetpack</a></p><p>In this article, I’ll demonstrate how can we implement similar behaviour in Flutter with SharedPreferences and ChangeNotifier.</p><h3>Ground Setup</h3><p>We’ll understand this with an example. Let’s say we’ve an app and it has two screens. ScreenA and ScreenB. We can save random value every time we click on the save button on the screens. Both screens have same UI for simplification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PmxVYhNMpNLHRMeZ20I0HQ.png" /></figure><p>Here, one whichever screen we click the button to save the random value, we always get the updated value on either screen. Let’s see how can we do it.</p><blockquote>This scenario can be similar to real world app where we update let’s say user profile and name on a screen and once we save those details, moving back to our home page should reflect the updated values.</blockquote><h3>App architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qo7tlbUDZqtzKP0yyS8Sg.png" /></figure><p>In the app, we’ll create a separate service for our preferences and then we’ll use this service within a change notifier to publish our changes as and when the value is saved or fetched directly.</p><h3>Dependencies required</h3><p>First step is to install the shared preference and provider dependencies as follows</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  ...<br>  shared_preferences: ^2.2.2  // preferences<br>  provider: ^6.1.2            // for change notifier provider feature</pre><h3>Preference service</h3><p>Now, let’s create our preference service and keep it as singleton.</p><pre>class PreferenceService {<br><br>  SharedPreferences? _sharedPreferences;<br><br>  PreferenceService._internal();<br><br>  factory PreferenceService() {<br>    return PreferenceService._internal();<br>  }<br><br>  Future&lt;SharedPreferences&gt; get _instance async {<br>    return _sharedPreferences ??= await SharedPreferences.getInstance();<br>  }<br><br>  save(String key, int value) async {<br>    final preference = await _instance;<br>    await preference.setInt(key, value);<br>  }<br><br>  Future&lt;int?&gt; fetch(String key) async {<br>    final preference = await _instance;<br>    return preference.getInt(key) ?? 0;<br>  }<br>}</pre><p>We defined a save and fetch functions which are async. This is quite straightforward and easy to understand.</p><h3>Notifier integration</h3><p>Now we’ll use the preference service in our notifier as follows</p><pre>class PreferenceNotifier extends ChangeNotifier {<br><br>  final PreferenceService _preferenceService = PreferenceService();<br>  ...<br>}</pre><p>For brevity, we’ll be saving a random integer value instead of actual data coming from either UI or some other layer but the fundamental remains the same.</p><pre>int? _randomValue;<br><br>save(String key, int value) async {<br>  await _preferenceService.save(key, value);<br>  _fetch(key);<br>}<br><br>// public getter for our UI<br>int get randomValue {<br>  // if the random value is null it means <br>  // we need to fetch it from local preference<br>  _randomValue ?? _fetch(&#39;key&#39;);<br>  return _randomValue ?? 0;<br>}<br><br>_fetch(String key) async {<br>  // fetch and save the value in the variable<br>  _randomValue = await _preferenceService.fetch(key);<br>  // notify the consumers<br>  notifyListeners();<br>}</pre><p>We’re done with the notifier. Now let’s move to our UI and see how can we consume it.</p><h3>Displaying data on UI</h3><p>Let’s create our screen A which contains screen name, a text showing the random value saved in the preference, a button to save the random value and a button to move to next screen.</p><pre>class PreferenceAScreen extends StatelessWidget {<br>  const PreferenceAScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Material(<br>      color: Colors.white,<br>      child: Column(<br>        crossAxisAlignment: CrossAxisAlignment.center,<br>        mainAxisAlignment: MainAxisAlignment.center,<br>        children: [<br>          const Text(<br>            &#39;Screen A&#39;,<br>            style: TextStyle(fontSize: 30),<br>          ),<br>          const SizedBox(<br>            height: 24,<br>          ),<br>          // main observer of our change notifier<br>          Consumer&lt;PreferenceNotifier&gt;(<br>            builder: (context, notifier, child) {<br>             return Text(&#39;${notifier.randomValue}&#39;, style: const TextStyle(fontSize: 24),);<br>            },<br>          ),<br>          const SizedBox(<br>            height: 24,<br>          ),<br>          ElevatedButton(<br>              onPressed: () {<br>                final randomValue = Random().nextInt(100);<br>                context.read&lt;PreferenceNotifier&gt;().save(&#39;key&#39;, randomValue);<br>              },<br>              child: const Text(&#39;Click to save&#39;)<br>          ),<br>          const SizedBox(<br>            height: 16,<br>          ),<br>          ElevatedButton(<br>              onPressed: () {<br>                Navigator.push(context, MaterialPageRoute(builder: (context) =&gt; const PreferenceBScreen()));<br>              },<br>              child: const Text(&#39;Move to Screen B&#39;)<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>The important part here is that the text that shows our saved value is kind of a observer or consumer of our notifier.</p><pre>Consumer&lt;PreferenceNotifier&gt;(<br>    builder: (context, notifier, child) {<br>        return Text(<br>                &#39;${notifier.randomValue}&#39;, <br>                style: const TextStyle(fontSize: 24)<br>         );<br>    },<br>),</pre><p>Every time anything changes in our preference, we’re notified on the UI and we fetch the latest saved value and show it. Same process happens on the Screen B which has same UI.</p><h3>Bamn!</h3><p>And that’s it! We’ve successfully made our preferences observable with notifier. This can helpful in many scenarios. We can add more to it and leverage the benefit.</p><p>Hope it’ll help you in some way!</p><p>Comment down to let me know if you have any inputs on this.</p><h3>That is all for now! Stay tuned!</h3><p>Connect with me (if the content is helpful to you ) on</p><ul><li><a href="https://saurabhpant.medium.com/">Medium</a></li><li><a href="https://github.com/aqua30">GitHub</a></li><li><a href="https://twitter.com/saurabh30pant">Twitter</a></li><li><a href="https://www.linkedin.com/in/saurabh-pant-44619057/">LinkedIn</a></li></ul><p>Until next time…</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab4ca00fbe2b" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/reflect-changes-in-async-from-local-storage-with-changenotifier-in-flutter-ab4ca00fbe2b">Reflect Changes in Async from Local Storage with ChangeNotifier in Flutter</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>