<?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 Raju Potharaju on Medium]]></title>
        <description><![CDATA[Stories by Raju Potharaju on Medium]]></description>
        <link>https://medium.com/@raju.debug?source=rss-8c33eac83e14------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*89FaifOVwIsoLivA64jc0Q.jpeg</url>
            <title>Stories by Raju Potharaju on Medium</title>
            <link>https://medium.com/@raju.debug?source=rss-8c33eac83e14------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:23:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raju.debug/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[       ?]]></title>
            <link>https://medium.com/@raju.debug/-80ff5c9c4c00?source=rss-8c33eac83e14------2</link>
            <guid isPermaLink="false">https://medium.com/p/80ff5c9c4c00</guid>
            <category><![CDATA[advertisement]]></category>
            <category><![CDATA[ssp]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[dsp]]></category>
            <category><![CDATA[programmatic-advertising]]></category>
            <dc:creator><![CDATA[Raju Potharaju]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 07:18:01 GMT</pubDate>
            <atom:updated>2024-11-10T07:18:01.819Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8_SwiFG7iWw965PszXCyg.png" /><figcaption>Ad-Flow-Diagram</figcaption></figure><p>Being a Software Engineer in the Ad-Tech space, I find this domain fascinating and full of complexity. Every ad you see is the result of countless interactions between ad servers, data providers, SSPs, DSPs, and exchanges. I work on systems where we serve at a scale of 𝟱𝟬𝟬 𝗕𝗶𝗹𝗹𝗶𝗼𝗻 𝗿𝗲𝗾𝘂𝗲𝘀𝘁 𝗺𝗼𝗻𝘁𝗵𝗹𝘆 (~𝟮𝟬𝗕 𝗿𝗲𝗾𝘂𝗲𝘀𝘁𝘀 𝗮 𝗱𝗮𝘆) 𝗺𝗲𝗮𝗻𝗶𝗻𝗴 𝗼𝘂𝗿 𝗤𝗣𝗦 𝗶𝘀 𝟮𝟬𝟬𝗞+</p><p>Let’s get back to our topic.</p><p>Every internet user sees ads while surfing, but have you ever wondered how these ads make their way to your screen? Here’s a quick overview of the magic behind online advertising! 🧙‍♂️✨</p><p>When you open a website or app, a chain reaction starts in milliseconds, bringing you personalized ads through a high-speed, complex process:</p><p>1️⃣ 𝗜𝗻𝘁𝗲𝗿𝗻𝗲𝘁 𝗨𝘀𝗲𝗿 → 2️⃣ 𝗣𝘂𝗯𝗹𝗶𝘀𝗵𝗲𝗿:<br>It starts with you, the internet user, visiting a website or app. That site or app is the publisher — think of popular blogs, news sites, or apps you use daily. These publishers provide the “space” for ads to appear, known as inventory.<br>Few examples of Publishers: <a href="https://www.linkedin.com/company/youtube/">YouTube</a>, <a href="https://www.linkedin.com/company/geeksforgeeks/">GeeksforGeeks</a>, <a href="https://www.linkedin.com/company/hindustantimes/">Hindustan Times</a>, <a href="https://www.linkedin.com/company/facebook/">Facebook</a>, <a href="https://www.linkedin.com/company/instagram/">Instagram</a>, <a href="https://www.linkedin.com/company/tiktok/">TikTok</a></p><p>3️⃣ 𝗦𝗦𝗣 (𝗦𝘂𝗽𝗽𝗹𝘆-𝗦𝗶𝗱𝗲 𝗣𝗹𝗮𝘁𝗳𝗼𝗿𝗺):<br>The publisher then connects with a supply-side platform (SSP), which acts as a marketplace that manages the publisher’s ad inventory. The SSP’s role is to make this inventory available for advertisers who may want to show you an ad.<br>Few examples of SSPs: <a href="https://www.linkedin.com/company/openx/">OpenX</a>, <a href="https://www.linkedin.com/company/pubmatic/">PubMatic</a>, <a href="https://www.linkedin.com/company/index-platform/">Index Exchange</a>, <a href="https://www.linkedin.com/company/colossus-ssp/">Colossus SSP</a></p><p>4️⃣ 𝗗𝗦𝗣 (𝗗𝗲𝗺𝗮𝗻𝗱-𝗦𝗶𝗱𝗲 𝗣𝗹𝗮𝘁𝗳𝗼𝗿𝗺):<br>On the other side, advertisers connect through a Demand-Side Platform (DSP), which helps them target audiences based on interests, demographics, and behavior. Advertisers use the DSP to find ad spaces (like the one on the site you’re visiting) and decide which ads should reach you.<br>Few examples of DSPs: <a href="https://www.linkedin.com/company/google-ads-/">Google Ads</a>, <a href="https://www.linkedin.com/company/the-trade-desk/">The Trade Desk</a>, <a href="https://www.linkedin.com/company/beeswaxio/">Beeswax (Acquired by Comcast)</a>, <a href="https://www.linkedin.com/company/bidswitch/">BidSwitch</a></p><p>𝗧𝗵𝗲 𝗥𝗲𝗮𝗹-𝗧𝗶𝗺𝗲 𝗕𝗶𝗱𝗱𝗶𝗻𝗴 (𝗥𝗧𝗕) 𝗔𝘂𝗰𝘁𝗶𝗼𝗻:<br>At this point, an auction begins, powered by Open Real-Time Bidding (ORTB) technology. The SSP and DSP communicate within fractions of a second, and advertisers bid for that ad spot. The winning bid determines which ad you ultimately see. 🚀</p><p>And there you have it! This seamless interaction between user, publisher, SSP, and DSP makes sure the right ad finds the right audience at the right time — 𝗮𝗹𝗹 𝗶𝗻 𝗺𝗶𝗹𝗹𝗶𝘀𝗲𝗰𝗼𝗻𝗱𝘀.</p><p>Do you have questions about how this system works? Comment below, and follow me for more insights on ad tech and scaling challenges!</p><p><em>❤ ❤ Thanks for reading this article ❤❤</em></p><p><em>If you find this blog informative do give a clap </em>👏 <em>below.</em></p><p><em>Let’s connect on </em><a href="https://linkedin.com/in/rajupotharaju155"><em>LinkedIn</em></a><em>.</em></p><p>Read my other blogs here:</p><ul><li><a href="https://medium.com/gytworkz/flutter-widget-lifecycle-everything-you-need-to-know-629d01ca4a09">Flutter Widget Lifecycle: Everything You Need to Know</a></li><li><a href="https://medium.com/gytworkz/how-to-integrate-platform-channels-in-flutter-a-step-by-step-tutorial-aa0ef85b08ab">How to Integrate Platform Channels in Flutter : A Step-by-Step Tutorial</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80ff5c9c4c00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shared Preferences in Flutter: Store and Retrieve data locally]]></title>
            <link>https://medium.com/gytworkz/shared-preferences-in-flutter-store-and-retrieve-data-locally-bbc937fabce4?source=rss-8c33eac83e14------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbc937fabce4</guid>
            <category><![CDATA[xml]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[local-database]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[sharedpreferences]]></category>
            <dc:creator><![CDATA[Raju Potharaju]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 10:42:30 GMT</pubDate>
            <atom:updated>2023-03-27T10:42:30.816Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3ePKN8Sgu0rbq1JJFCgvQ.png" /><figcaption>Blog Banner</figcaption></figure><p>Store and retrieve data locallyFlutter is a popular framework for building cross-platform mobile applications. One of the essential features in mobile development is the ability to store data persistently across app sessions. Shared preferences in Flutter are one way to store and retrieve data in a key-value pair format. In this blog, we will explore what shared preferences are and how to use them in Flutter with examples.</p><h3>What are Shared Preferences in Flutter?</h3><p>Shared preferences are key-value pairs used to store and retrieve data in a Flutter application. They are often used to store <strong>simple</strong> user preferences, such as language settings, font size, or theme colors. Shared preferences are stored in the device’s file system and are persistent across app sessions.</p><p>Data once stored in shared preferences remain in the device&#39;s local storage, hence data can be retrieved whenever the app is launched. <strong>But Shared Preferences data is lost whenever the App Data is deleted or the App is uninstalled from the device.</strong></p><p>Shared preferences are commonly used in Flutter applications because they are easy to use and provide a simple way to store and retrieve data. They are also lightweight and can store small amounts of data. Shared preferences data is stored in <strong>XML Format.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9LzVai06J6Zs2ymyyVMQw.png" /><figcaption>Shared Preferences supported data types</figcaption></figure><h3>How to use Shared Preferences in Flutter</h3><p>Shared preferences <strong>should be used only</strong> to store simple data like String, int, bool, etc, and <strong>NOT</strong> complex data like a dictionary / JSON / List of objects received from API.</p><p>To use Shared Preferences in Flutter, you need to add the following dependency to your pubspec.yaml file:</p><pre>dependencies:<br>  shared_preferences: ^2.0.12</pre><p>Then, run the command flutter packages get in your terminal to install the package.</p><p>Once you have added the shared_preferences package, you can use it in your Flutter application.</p><p>To store data in Shared Preferences, you need to follow these steps:</p><ol><li>Get an instance of SharedPreferences</li><li>Store data in SharedPreferences</li><li>Retrieve data from SharedPreferences</li></ol><p>Let’s go through each step with examples.</p><h3>Step 1: Get an instance of SharedPreferences</h3><p>To get an instance of SharedPreferences, you can use the getInstance() method from the SharedPreferences class. Here&#39;s an example:</p><pre>import &#39;package:shared_preferences/shared_preferences.dart&#39;;<br><br>SharedPreferences preferences = await SharedPreferences.getInstance();<br></pre><p>The await keyword is used to wait for the getInstance() method to complete before returning the SharedPreferences instance.</p><h3>Step 2: Store data in SharedPreferences</h3><p>To store data in SharedPreferences, you can use the set&lt;Type&gt;(key, value) method, where Type can be String, int, double, bool, or List&lt;String&gt;. Here&#39;s an example:</p><pre>SharedPreferences preferences = await getSharedPreferencesInstance();<br><br>preferences.setString(&#39;username&#39;, &#39;johndoe&#39;);<br>preferences.setInt(&#39;age&#39;, 30);<br>preferences.setBool(&#39;isLogged&#39;, true);</pre><p>In the example above, we store a String, an int, and a bool in SharedPreferences using the setString, setInt and setBool methods.</p><h3>Step 3: Retrieve data from SharedPreferences</h3><p>To retrieve data from SharedPreferences, you can use the get&lt;Type&gt;(key) method, where Type is the type of value you want to retrieve. Here&#39;s an example:</p><pre>SharedPreferences preferences = await getSharedPreferencesInstance();<br><br>String username = preferences.getString(&#39;username&#39;);<br>int age = preferences.getInt(&#39;age&#39;);<br>bool isLogged = preferences.getBool(&#39;isLogged&#39;);</pre><p>In the example above, we retrieve the String, int, and bool values we stored earlier using the getString, getInt and getBool methods.</p><h3>Step 4: Delete data from SharedPreferences</h3><p>To retrieve data from SharedPreferences, you can use the remove(key) method, where key is the name of the data you want to remove. Here&#39;s an example:</p><pre>SharedPreferences preferences = await getSharedPreferencesInstance();<br><br>preferences.remove(&#39;username&#39;);<br>preferences.remove(&#39;age&#39;);<br>preferences.remove(&#39;isLogged&#39;);</pre><h3>Step 5: To Check whether a value is present or not?</h3><p><strong>containsKey</strong> used to check value is present or not.</p><pre>SharedPreferences preferences = await getSharedPreferencesInstance();<br><br>bool checkValue = preferences.containsKey(&#39;age&#39;);</pre><p><strong>containsKey</strong> will give a boolean value, true for present and false for not present.</p><h3>Conclusion</h3><p>In this blog, we discussed how to use Shared Preferences in Flutter with examples. We learned how to get an instance of SharedPreferences, store retrieve and check if data exists in SharedPreferences. Shared Preferences is a simple and easy-to-use way to store and retrieve simple data in Flutter.</p><p><em>❤ ❤ Thanks for reading this article ❤❤</em></p><p><em>If you find this blog informative do give a clap </em>👏 <em>below.</em></p><p><em>Let&#39;s connect on </em><a href="https://linkedin.com/in/rajupotharaju155"><em>LinkedIn</em></a><em>.</em></p><p>Read my other blogs here:</p><ul><li><a href="https://medium.com/gytworkz/how-to-integrate-platform-channels-in-flutter-a-step-by-step-tutorial-aa0ef85b08ab">How to Integrate Platform Channels in Flutter : A Step-by-Step Tutorial</a></li><li><a href="https://medium.com/gytworkz/flutter-widget-lifecycle-everything-you-need-to-know-629d01ca4a09">Flutter Widget Lifecycle: Everything You Need to Know</a></li><li><a href="https://medium.com/gytworkz/deep-dive-into-flutter-app-lifecycle-342b797480aa">Deep dive into Flutter App Lifecycle.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbc937fabce4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gytworkz/shared-preferences-in-flutter-store-and-retrieve-data-locally-bbc937fabce4">Shared Preferences in Flutter: Store and Retrieve data locally</a> was originally published in <a href="https://medium.com/gytworkz">GYTWorkz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hive Database in Flutter: Store and Retrieve data Locally]]></title>
            <link>https://medium.com/gytworkz/hive-database-in-flutter-store-and-retrieve-data-locally-d53b333d74ee?source=rss-8c33eac83e14------2</link>
            <guid isPermaLink="false">https://medium.com/p/d53b333d74ee</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[local-database]]></category>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Raju Potharaju]]></dc:creator>
            <pubDate>Mon, 27 Mar 2023 10:42:14 GMT</pubDate>
            <atom:updated>2023-03-27T12:58:14.255Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9cIU3j6FVjRuc8CENwuVA.png" /><figcaption>Blog Banner</figcaption></figure><p>Flutter is a popular mobile application development framework that allows developers to create high-performance applications for both Android and iOS platforms. When it comes to data storage in Flutter, there are several options available such as SQLite, Shared Preferences, and Hive.</p><p><strong>Hive</strong> is a lightweight and fast NoSQL database that can be used to store data in Flutter applications. In this blog, we will explore how to setup and use Hive database in Flutter.</p><p>In this article, we’ll go over these steps to build a simple CRUD app that stores cats data with hive:</p><ul><li><strong>Setup Hive</strong></li><li><strong>Type Adapters</strong></li><li><strong>Storing data</strong></li><li><strong>Reading data</strong></li><li><strong>Update and Delete data</strong></li></ul><p>So let&#39;s get started! OKE?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*kQsNP3M648GrV_COEta30w.gif" /></figure><p>Before we begin with Setting up Hive, we need to set up our Flutter project, which I already did, and put it in the <strong>lib/hive_db_blog</strong> folder in my <a href="https://github.com/rajupotharaju155/flutter_blogs">Github</a> repo, it contains the UI and the provider setup. You can clone it from there.</p><p><a href="https://github.com/rajupotharaju155/flutter_blogs">GitHub - rajupotharaju155/flutter_blogs: This repository contains the code for my blogs written on Medium and other platforms</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*f1FixxQi9StxXM_krGVrNA.png" /><figcaption>Hive Implementation UI</figcaption></figure><h3>Step 1. Setup Hive</h3><p>To use Hive in Flutter, we need to add the following dependencies to the pubspec.yaml file:</p><pre>dependencies:<br>  hive: ^2.2.3<br>  hive_flutter: ^1.1.0</pre><p>we also need to add hive_generator and build_runner to the dev dependencies:</p><pre>dev_dependencies:<br>  hive_generator: ^2.0.0<br>  build_runner: ^2.3.3</pre><p>Next, we need to initialize Hive in the main() function of our Flutter application. We can do this by calling the Hive.initFlutter() method as shown below:</p><pre>void main() async {<br>  await Hive.initFlutter();<br>  runApp(const MyApp());<br>}</pre><h3>Step 2: Define Hive Type Adapters</h3><p>Hive is a NoSQL database that stores data in key-value pairs. Where value can be of a different type such as<strong> int, string, list, or custom objects</strong>. To store custom objects in Hive, we need to define type adapters that tell Hive how to serialize and deserialize our objects. We can use the hive_generator package to generate type adapters for our custom objects automatically.</p><p>This means we will create a model class and store that entire modal in Hive. My model class is called as cat_model.dart</p><pre>class CatModel{<br>  final String name;<br>  final String age;<br>  final bool isMale;<br><br>  const CatModel(this.name, this.age, this.isMale);<br>}</pre><p>It&#39;s a simple model class. let&#39;s make it compatible with Hive by tweaking it a little.</p><pre>import &#39;package:hive/hive.dart&#39;;<br>part &#39;cat_model.g.dart&#39;;<br><br>@HiveType(typeId: 0)<br>class CatModel {<br><br>  @HiveField(0)<br>  final String name;<br><br>  @HiveField(1)<br>  final String age;<br><br>  @HiveField(2)<br>  final bool isMale;<br><br>  const CatModel(this.name, this.age, this.isMale);<br>}</pre><ul><li>Annotate the model class with @HiveType(), so the generator knows this should be a TypeAdapter.</li><li>Annotate each field you want to save with @HiveField(index), the index is an int and each index should appear once and you shouldn&#39;t change it after registering them.</li><li>In case you change the field name or its datatype or add a new field — You have to run the type adapter command again and <strong>re-run the app to reflect the changes</strong> in the app.</li></ul><p>We can then generate the type adapters for this class by running the following command in the terminal:</p><pre>flutter packages pub run build_runner build</pre><p>This will generate a cat_model.g.dart file that contains the type adapter for our CatModel class.</p><p>Finally, register the type adapter in your main function, just add it beneath your hive initialization.</p><pre>void main() async {<br>  await Hive.initFlutter();<br>  Hive.registerAdapter(CatModelAdapter());<br>  runApp(const MyApp());<br>}</pre><h3>Step 3: Storing Data in Hive</h3><p>To store data in Hive, we need to open a Hive box. A box is similar to a table in a traditional SQL database and stores key-value pairs. We can open a box by calling the Hive.openBox() method and passing in the name of the box as a parameter. For example, we can open a box named cats as shown below:</p><pre>Hive.openBox&lt;CatModel&gt;(&#39;cats&#39;);</pre><p>We can open the same box multiple times, returning us the same box instance. However, it is good practice to open it once on app launch and get the box whenever we want to add/update/delete data from it. To get the cat box, we can do the following:</p><pre>Box&lt;CatModel&gt; catBox = Hive.box&lt;CatModel&gt;(&#39;cats&#39;);</pre><p>And there are 2 ways to add data</p><ul><li>box.add(value) - just gives each value an index and auto increments it.</li><li>box.put(&#39;key&#39;, value) - you have to specify the key for each value</li></ul><p>Now we can add data to it by creating a new instance of the CatModel class. and add it to Hive database using put() method</p><p>For example, we can add a new cat to the box as shown below:</p><pre>var catModel = CatModel(&#39;foo&#39;, 4 , true); //creating object<br>await catBox.put(catModel.name, catModel); //putting object into hive box</pre><p>In this example, we have added a new cat with a key same as its name foo to the catBox box.</p><h3>Step 4: Reading Data from Hive</h3><p>There are different ways to read data from your boxes:</p><ul><li>box.get(&#39;key) - get the value from a key.</li><li>box.getAt(index) - get the value from an index created with box.add().</li><li>box.values - this returns an iterable containing all the items in the box.</li></ul><pre>CatModel? catModel = catBox.get(&#39;foo&#39;); //get by key<br>CatModel? catModel = catBox.getAt(3); //get by index<br>List&lt;CatModel&gt; catModelList = catBox.values.toList(); //get all items in list</pre><p>We will use the third method to get all the cats that we have added so far.</p><h3>Step 5: Updating Data in Hive</h3><p>To update you can use box.put(&#39;key&#39;, newValue) to update that value, or box.putAt(index, item) which works like getAt()</p><p>for example, let us update the age of our previous cat foo</p><pre>var catModel = CatModel(&#39;foo&#39;, 5, true); //creating new object <br>await catBox.put(catModel.name, catModel); //putting object into hive box</pre><p>When we put in a new model with the same key, the old data gets updated.</p><h3>Step 6: Deleting Data from Hive</h3><p>Deleting items is similar to getting:</p><ul><li>box.delete(&#39;key) - delete by key</li><li>box.deleteAt(index) - delete by index</li><li>box.deleteAll(keys) - accepts an iterable of keys, and deletes all the keys given.</li></ul><pre>Box&lt;CatModel&gt; catBox = await HiveBoxHelperClass.openCatBox();<br>await catBox.delete(&#39;foo&#39;); //delete cat with key (name) as &#39;foo&#39;</pre><p>Hurray!, we have successfully completed our ‘C’ ‘R’ ‘U’ ‘D’ in Local database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*F9xk0lLbLoKKeQ6mFPdpTw.gif" /></figure><h3>Conclusion</h3><p>Hive is a lightweight and fast NoSQL database that can be used to store data in Flutter applications. In this blog, we have explored how to set up and use Hive in Flutter, including defining Hive type adapters, and storing, reading, updating, and deleting data from Hive. By using Hive in our Flutter applications, we can easily store and retrieve data without the overhead of traditional SQL databases.</p><p><em>❤ ❤ Thanks for reading this article ❤❤</em></p><p><em>If you find this blog informative do give a clap </em>👏 <em>below.</em></p><p><em>Let&#39;s connect on </em><a href="https://linkedin.com/in/rajupotharaju155"><em>LinkedIn</em></a><em>.</em></p><p>Read my other blogs here:</p><ul><li><a href="https://medium.com/gytworkz/how-to-integrate-platform-channels-in-flutter-a-step-by-step-tutorial-aa0ef85b08ab">How to Integrate Platform Channels in Flutter : A Step-by-Step Tutorial</a></li><li><a href="https://medium.com/gytworkz/flutter-widget-lifecycle-everything-you-need-to-know-629d01ca4a09">Flutter Widget Lifecycle: Everything You Need to Know</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d53b333d74ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gytworkz/hive-database-in-flutter-store-and-retrieve-data-locally-d53b333d74ee">Hive Database in Flutter: Store and Retrieve data Locally</a> was originally published in <a href="https://medium.com/gytworkz">GYTWorkz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate Platform Channels in Flutter : A Step-by-Step Tutorial]]></title>
            <link>https://medium.com/gytworkz/how-to-integrate-platform-channels-in-flutter-a-step-by-step-tutorial-aa0ef85b08ab?source=rss-8c33eac83e14------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa0ef85b08ab</guid>
            <category><![CDATA[platform-channel]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Raju Potharaju]]></dc:creator>
            <pubDate>Thu, 09 Mar 2023 04:52:15 GMT</pubDate>
            <atom:updated>2023-03-26T10:48:46.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQ5c_zogb64vQWPkuiMD_Q.png" /><figcaption>Blog Banner</figcaption></figure><p>Flutter is a cross-platform toolkit, yet it allows you the full power of native platform APIs in a very simple way. Even if you don’t have any past experience writing native code, be scared no more.</p><p>In this blog post, we will explore platform channels in Flutter and how they can be used to interact with platform-specific features or native APIs.</p><p>PS: You can find the code for this article in <strong>lib/platform_channels</strong> folder in my <a href="https://github.com/rajupotharaju155/flutter_blogs">Github</a> repo.</p><p><a href="https://github.com/rajupotharaju155/flutter_blogs">GitHub - rajupotharaju155/flutter_blogs: This repository contains the code for my blogs written on Medium and other platforms</a></p><h3><strong>What are Platform Channels?</strong></h3><p>Platform channels are a feature in Flutter that allows developers to interact with platform-specific code. With platform channels, developers can send messages from their Flutter app to the native code on the platform, and vice versa. This makes it possible to access platform-specific features that are not available through Flutter’s core APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*qwvnLdUWK2EMx28vnntU6w.png" /></figure><h3><strong>Why Platform Channels?</strong></h3><p>Let’s imagine a common use-case. A client wants to integrate with a 3rd-party provider. This provider doesn’t have support for Flutter yet, but they have an iOS and Android SDK. In such case, you will need to call these SDKs from Flutter.</p><p>For example, you may want to access the device’s camera or microphone, or access a native library that is not available in Flutter. Platform channels make it possible to access these features by creating a bridge between the Flutter app and the native code on the platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*Dg1DDV-84Tn0-iSD5Sb5qg.png" /><figcaption>Example: Platform Channel Bridge</figcaption></figure><h3>Setting up Platform Channels</h3><p>To use platform channels in Flutter, you need to define a channel (bridge) that connects your Flutter app to the native code. The channel is defined by a name, this name is a <strong>String</strong>, if you misspelled it in either side of the channel, you won’t be able to reach out to the other side.</p><p>There are 2 types of platform channels:</p><ul><li><a href="https://api.flutter.dev/flutter/services/MethodChannel-class.html">MethodChannel</a>: a channel used to communicate with the platform using asynchronous method calls. Think of it as a Future.</li><li><a href="https://api.flutter.dev/flutter/services/EventChannel-class.html">EventChannel</a>: a channel used to listen to event streams from the platform. Think of it as a Stream.</li></ul><h3>MethodChannel</h3><h3>Step 1: Create the Flutter platform client</h3><pre>// Give it a name.<br>const _channelName = &#39;app.id.com/my_channel_name&#39;;<br><br>// Construct it.<br>final _channel = const MethodChannel(_channelName);</pre><p>Once you have a MethodChannel object ready, you can call any method by its name:</p><pre>dynamic returnValue = await methodChannelPlatform.invokeMethod(&quot;addnumbers&quot;);</pre><p>if you want to pass arguments to this method you can do it as follows.</p><pre>    dynamic returnValue = await methodChannelPlatform<br>            .invokeMethod(&quot;addnumbers&quot;, &lt;String, dynamic&gt;{<br>                &#39;n1&#39;: 50,<br>                &#39;n2&#39;: 10,<br>            });</pre><p>In this example we define channel name as ‘app.id.com/my_channel_name’ and method name as “addnumbers” which is first argument and second argument being the values that you want to pass to android/iOS side, here we are passing n1 and n2.</p><p>Complete code from Flutter side looks like this.</p><pre>  dynamic additionResult = 0;<br><br>  static const methodChannelPlatform =<br>      MethodChannel(&quot;app.id.com/my_channel_name&quot;);<br><br>  void _invokeAddNumbers() async {<br>    dynamic returnValue = await methodChannelPlatform<br>        .invokeMethod(&quot;addnumbers&quot;, &lt;String, dynamic&gt;{<br>      &#39;n1&#39;: 50,<br>      &#39;n2&#39;: 10,<br>    });<br>    setState(() {<br>      additionResult = returnValue;<br>    });<br>  }</pre><h3>Step 2: Android platform-specific implementation</h3><ol><li>Start android Studio</li><li>Open the file MainActivity.kt located in the my_flutter_app/android/app/src/main/kotlin/ <strong>folder</strong> in the Project view.</li><li>Inside the configureFlutterEngine() method, create a MethodChannel and call setMethodCallHandler(). Make sure to use the same channel name as was used on the Flutter client side.</li></ol><pre>class MainActivity: FlutterActivity() {<br>    private val channel = &quot;app.id.com/my_channel_name&quot;;<br><br>    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {<br>        super.configureFlutterEngine(flutterEngine)<br>        MethodChannel(flutterEngine.dartExecutor, channel)<br>            .setMethodCallHandler { call, result -&gt;<br>                // execute android side code here<br>            }<br>    }<br>}</pre><p>Here we will implement Kotlin-level logic to access the method invoked from flutter, process, and return the response back to Flutter.</p><pre>    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {<br>        super.configureFlutterEngine(flutterEngine)<br>        MethodChannel(flutterEngine.dartExecutor, channel)<br>            .setMethodCallHandler{<br>                call, result -&gt;<br>                    if(call.method == &quot;addnumbers&quot;){<br>                        val sum: Int = addNumbers(call); // function is written separately,<br>                        result.success(hashMapOf(<br>                            &quot;Sum&quot; to sum,<br>                        ));<br>                    }else{<br>                        result.notImplemented()<br>                    }<br><br>            }<br>    }</pre><p>In the above example, call.method == “addnumbers”, the identifier “addnumbers” has to be the same as the method name declared on flutter side.</p><p>The complete code from Android side is as follows:</p><pre>class MainActivity: FlutterActivity() {<br>    private val channel = &quot;app.id.com/my_channel_name&quot;;<br><br>    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {<br>        super.configureFlutterEngine(flutterEngine)<br>        MethodChannel(flutterEngine.dartExecutor, channel)<br>            .setMethodCallHandler { call, result -&gt;<br>                if (call.method == &quot;addnumbers&quot;) {<br>                    val sum: Int = addNumbers(call); // function is written separately,<br>                    result.success(<br>                        hashMapOf(<br>                            &quot;Sum&quot; to sum,<br>                        )<br>                    );<br>                } else {<br>                    result.notImplemented()<br>                }<br><br>            }<br>    }<br><br>    private fun addNumbers(call: MethodCall): Int {<br>        val args = call.arguments as Map&lt;String, Any&gt;<br>        val a = args[&quot;n1&quot;] as Int;<br>        val b = args[&quot;n2&quot;] as Int;<br>        val sum: Int = a + b;<br>        return sum;<br>    }<br><br>}</pre><p>Here we are accessing the “n1” and “n2” values sent from flutter, processing them, and returning the response in form of JSON.</p><h3>Step 3: iOS platform-specific implementation</h3><ol><li>Start Xcode</li><li>Open ios folder in your flutter project in Xcode.</li><li>Open the file AppDelegate.swift located under <strong>Runner &gt; Runner</strong> in the Project navigator.</li><li>Override the application:didFinishLaunchingWithOptions: function and create a FlutterMethodChannel tied to the channel name app.id.com/my_channel_name.</li></ol><pre>@UIApplicationMain<br>@objc class AppDelegate: FlutterAppDelegate {<br>    override func application(<br>        _ application: UIApplication,<br>        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>    ) -&gt; Bool {<br>        <br>        let controller : FlutterViewController = window?.rootViewController as! FlutterViewController<br>        let myChannnel = FlutterMethodChannel(<br>            name: &quot;app.id.com/my_channel_name&quot;,<br>            binaryMessenger: controller.binaryMessenger)<br>        <br>        myChannnel.setMethodCallHandler({<br>            (call: FlutterMethodCall, result: @escaping FlutterResult) -&gt; Void in<br>            // execute iOS side code here<br>        })<br>        <br>        GeneratedPluginRegistrant.register(with: self)<br>        return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>    }<br>}</pre><p>Here we will implement iOS-level logic to access the method invoked from flutter, process, and return the response back to Flutter.</p><pre>@UIApplicationMain<br>@objc class AppDelegate: FlutterAppDelegate {<br>    override func application(<br>        _ application: UIApplication,<br>        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>    ) -&gt; Bool {<br>        <br>        let controller : FlutterViewController = window?.rootViewController as! FlutterViewController<br>        let myChannnel = FlutterMethodChannel(<br>            name: &quot;app.id.com/my_channel_name&quot;,<br>            binaryMessenger: controller.binaryMessenger)<br>        <br>        myChannnel.setMethodCallHandler({<br>            (call: FlutterMethodCall, result: @escaping FlutterResult) -&gt; Void in<br>            <br>            if(call.method == &quot;addnumbers&quot;){<br>                let c: Int = self.addNumber(call: call) // function is written separately<br>                let finalResult: [String: Int] = [&quot;Sum&quot; : c]<br>                result(finalResult)<br>            }else{<br>                result(FlutterMethodNotImplemented)<br>            }<br>        })<br>        <br>        <br>        GeneratedPluginRegistrant.register(with: self)<br>        return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>    }<br>}</pre><p>In the above example, call.method == “addnumbers”, the identifier “addnumbers” has to be the same as the method name declared on the flutter side.</p><p>The complete code from iOS side is as follows:</p><pre>@UIApplicationMain<br>@objc class AppDelegate: FlutterAppDelegate {<br>    override func application(<br>        _ application: UIApplication,<br>        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>    ) -&gt; Bool {<br>        <br>        let controller : FlutterViewController = window?.rootViewController as! FlutterViewController<br>        let myChannnel = FlutterMethodChannel(<br>            name: &quot;app.id.com/my_channel_name&quot;,<br>            binaryMessenger: controller.binaryMessenger)<br>        <br>        myChannnel.setMethodCallHandler({<br>            (call: FlutterMethodCall, result: @escaping FlutterResult) -&gt; Void in<br>            <br>            if(call.method == &quot;addnumbers&quot;){<br>                let c: Int = self.addNumber(call: call) // function is written separately<br>                let finalResult: [String: Int] = [&quot;Sum&quot; : c]<br>                result(finalResult)<br>            }else if(call.method == &quot;getbatterylevel&quot;){<br>                self.receiveBatteryLevel(result: result)<br>            }else{<br>                result(FlutterMethodNotImplemented)<br>            }<br>        })<br>        <br>        <br>        GeneratedPluginRegistrant.register(with: self)<br>        return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>    }<br>    <br>    <br>    func addNumber(call: FlutterMethodCall) -&gt; Int {<br>        let args = call.arguments as? Dictionary&lt;String, Any&gt;<br>        let a = args?[&quot;n1&quot;] as! Int<br>        let b = args?[&quot;n2&quot;] as! Int<br>        print(a as Int)<br>        print(b as Int)<br>        let c = a + b<br>        return c;<br>    }<br>}</pre><p>Here we are accessing the “n1” and “n2” values sent from flutter, processing them and returning the response in form of json.</p><p>When the native code receives the message, it can perform the necessary actions and send a response back to the Flutter app. In this case, the native code would return the battery level as an integer, which is then converted to a string and displayed in the UI.</p><h3>Conclusion</h3><p>In this article, we learned how to create the bridge or channel between Flutter ←→ Android and Flutter ←→ iOS and address problems by communicating with the native code.</p><p>Platform channels are a powerful feature in Flutter that enables us to interact with platform-specific code. We can create high-quality, cross-platform applications that take full advantage of the features of each platform.</p><p><em>❤ ❤ Thanks for reading this article ❤❤</em></p><p><em>If you find this blog informative do give a clap </em>👏 <em>below.</em></p><p><em>Let&#39;s connect on </em><a href="https://linkedin.com/in/rajupotharaju155"><em>LinkedIn</em></a><em>.</em></p><p>Read my other blogs here:</p><ul><li><a href="https://medium.com/gytworkz/flutter-widget-lifecycle-everything-you-need-to-know-629d01ca4a09">Flutter Widget Lifecycle: Everything You Need to Know</a></li><li><a href="https://medium.com/gytworkz/advanced-animation-techniques-in-flutter-972c2fdff6ff">Advanced animation techniques in Flutter</a></li><li><a href="https://medium.com/gytworkz/integrating-flutter-with-apis-and-external-services-e8a5efb9da67">Integrating Flutter with APIs and external services</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa0ef85b08ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gytworkz/how-to-integrate-platform-channels-in-flutter-a-step-by-step-tutorial-aa0ef85b08ab">How to Integrate Platform Channels in Flutter : A Step-by-Step Tutorial</a> was originally published in <a href="https://medium.com/gytworkz">GYTWorkz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Widget Lifecycle: Everything You Need to Know]]></title>
            <link>https://medium.com/gytworkz/flutter-widget-lifecycle-everything-you-need-to-know-629d01ca4a09?source=rss-8c33eac83e14------2</link>
            <guid isPermaLink="false">https://medium.com/p/629d01ca4a09</guid>
            <category><![CDATA[lifecycle-methods]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[widget]]></category>
            <dc:creator><![CDATA[Raju Potharaju]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 04:35:13 GMT</pubDate>
            <atom:updated>2023-03-06T04:35:13.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sADSH89-eJ2vYqEGO1_Lxg.png" /><figcaption>Blog Banner</figcaption></figure><p>Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time. It is a combination of stateful and stateless widgets. Understanding the widget lifecycle is crucial for developing high-quality Flutter applications.</p><p>In this blog post, we will learn about <strong>widget lifecycle in Flutter</strong> with examples to help you understand how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*i4BhVQPDcv8mspZ1TOP4_g.gif" /></figure><p>Before diving into Widget Lifecycle, Let us understand what does this widget means and what are the types of widgets in Flutter.</p><h3><strong>What is a Widget?</strong></h3><p>A widget is a building block of a Flutter application. It can be anything from a button to a complex UI component. Widgets are used to construct the user interface of the application. Flutter applications are made up of a tree of widgets. Each widget has its own properties and can be nested within other widgets.</p><p>I have explained Widget in detail <a href="https://medium.com/gytworkz/understanding-flutter-widgets-and-architecture-98ee1f209b96">here</a>.</p><blockquote><em>There are two types of widgets in Flutter.</em></blockquote><ul><li>Stateless Widgets.</li><li>Stateful Widgets.</li></ul><p>=&gt; <strong>Stateless Widgets</strong> do not contain states hence they can be updated only when its parent changes. Once created, stateless widgets cannot be updated means they are immutable, they have to be created again by supplying new data in order to see the changes.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() =&gt; runApp(MyApp());<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Container();<br>  }<br>}</pre><p><strong>=&gt; Stateful Widgets</strong> can hold the states internally, so it can be updated whenever its states changes and also whenever its parent changes. It is mutable widget, so it can be drawn multiple times in its lifetime.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() =&gt; runApp(MyApp());<br><br>class MyApp extends StatefulWidget {<br>  @override<br>  _MyAppState createState() =&gt; _MyAppState();<br>}<br><br>class _MyAppState extends State&lt;MyApp&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Container();<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*l6eYYaFLwAs8j9Miuo5XrA.jpeg" /><figcaption>Lifecycle of Widgets</figcaption></figure><h3>What are Widget Lifecycle Methods:</h3><p>The widget lifecycle is a sequence of events that occur when a widget is created, updated, or destroyed. Understanding the widget lifecycle is important for writing efficient Flutter applications.</p><blockquote><em>createState()</em></blockquote><blockquote><em>initState()</em></blockquote><blockquote><em>didChangeDependencies()</em></blockquote><blockquote><em>build()</em></blockquote><blockquote><em>didUpdateWidget()</em></blockquote><blockquote><em>setState()</em></blockquote><blockquote><em>deactivate()</em></blockquote><blockquote><em>dispose()</em></blockquote><ul><li>createState(): This method creates the state object for the widget. When we create a stateful widget, our framework calls a createState() method and it must be overridden.</li></ul><pre>class MyPage extends StatefulWidget {<br>  @override<br>  _MyPageState createState() =&gt; _MyScreenState();<br>}</pre><ul><li>initState(): This method is called after the state object is created. It is used to initialise the state of the widget.</li></ul><pre>late int _counter;<br>@override<br>void initState() {<br>  print(&quot;initState&quot;);<br>  _counter = 0;<br>  super.initState();<br>}</pre><ul><li>build(): This method is called after the state object is initialised. It is used to build the widget tree. This gets called each time the widget is rebuilt this can happen after initState, didChangeDependencies, didUpdateWidget, or when the state is changed via a call to setState.</li></ul><pre>  @override<br>  Widget build(BuildContext context) {<br>    print(&quot;build&quot;);<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&quot;Lifecycle Demo&quot;),<br>      ),<br>      body: Container(<br>          child: Column(<br>        children: [<br>          Text(_counter.toString()),<br>          ElevatedButton(onPressed: _increment, child: const Text(&quot;Increment&quot;))<br>        ],<br>      )),<br>    );<br>  }</pre><ul><li>didChangeDependencies(): This method is called immediately after <em>initState </em>and when dependency of the State object changes via InheritedWidget.</li></ul><pre>  @override<br>  void didChangeDependencies() {<br>    print(&quot;didChangeDependencies&quot;);<br>    super.didChangeDependencies();<br>  }</pre><ul><li>didUpdateWidget(): This method is called when the widget is updated with new properties. A typical case is when a parent passes some variable to the children() widget via the constructor.</li></ul><pre>  @override<br>  void didUpdateWidget(covariant MyPage oldWidget) {<br>    print(&quot;didUpdateWidget&quot;);<br>    super.didUpdateWidget(oldWidget);<br>  }</pre><ul><li>deactivate()<strong>: </strong>This method is invoked whenState is removed from subtree A and reinserted to subtree B with the use of a GlobalKey.</li></ul><pre>  @override<br>  void deactivate() {<br>    print(&quot;deactivate&quot;);<br>    super.deactivate();<br>  }</pre><ul><li>dispose()<strong>: </strong>This method is called when the widget is about to be destroyed permanently. It is used to release any resources used by the widget like closing network connections or stopping animations.</li></ul><pre>  @override<br>  void dispose() {<br>    print(&quot;dispose&quot;);<br>    super.dispose();<br>  }</pre><p><strong>Code File</strong></p><pre><br>class MyPage extends StatefulWidget {<br>  const MyPage({super.key});<br><br>  @override<br>  State&lt;MyPage&gt; createState() {<br>    print(&quot;createState&quot;);<br>    return _MyPageState();<br>  }<br>}<br><br>class _MyPageState extends State&lt;MyPage&gt; {<br>  void _increment() {<br>    setState(() {<br>      _counter = _counter + 1;<br>    });<br>  }<br><br>  late int _counter;<br>  @override<br>  void initState() {<br>    print(&quot;initState&quot;);<br>    _counter = 0;<br>    super.initState();<br>  }<br><br>  @override<br>  void didChangeDependencies() {<br>    print(&quot;didChangeDependencies&quot;);<br>    super.didChangeDependencies();<br>  }<br><br>  @override<br>  void didUpdateWidget(covariant MyPage oldWidget) {<br>    print(&quot;didUpdateWidget&quot;);<br>    super.didUpdateWidget(oldWidget);<br>  }<br><br>  @override<br>  void dispose() {<br>    print(&quot;dispose&quot;);<br>    super.dispose();<br>  }<br><br>  @override<br>  void deactivate() {<br>    print(&quot;deactivate&quot;);<br>    super.deactivate();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    print(&quot;build&quot;);<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&quot;Lifecycle Demo&quot;),<br>      ),<br>      body: Container(<br>          child: Column(<br>        children: [<br>          Text(_counter.toString()),<br>          ElevatedButton(onPressed: _increment, child: const Text(&quot;Increment&quot;))<br>        ],<br>      )),<br>    );<br>  }<br>}</pre><p>Order of lifecycle methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*KNo1bqjpeyMhLDobX82JQw.png" /><figcaption>Order of lifecycle methods</figcaption></figure><h3><strong>Conclusion</strong></h3><p>In conclusion, understanding the widget lifecycle is essential for building high-quality Flutter applications. Remember that widgets are the building blocks of a Flutter application, and <strong>each widget has its own lifecycle</strong>. By mastering the widget lifecycle, you can build more efficient and effective Flutter applications.</p><p><em>❤ ❤ Thanks for reading this article ❤❤</em></p><p><em>If you find this blog informative do give a clap </em>👏 <em>below.</em></p><p><em>Lets connect of </em><a href="https://linkedin.com/in/rajupotharaju155"><em>LinkedIn</em></a><em>.</em></p><p>I have written <a href="https://medium.com/gytworkz/deep-dive-into-flutter-app-lifecycle-342b797480aa">this blog</a> in which I have explained everything about Flutter app lifecycles (Not the same as Widget lifecycle)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=629d01ca4a09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gytworkz/flutter-widget-lifecycle-everything-you-need-to-know-629d01ca4a09">Flutter Widget Lifecycle: Everything You Need to Know</a> was originally published in <a href="https://medium.com/gytworkz">GYTWorkz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep dive into Flutter App Lifecycle.]]></title>
            <link>https://medium.com/gytworkz/deep-dive-into-flutter-app-lifecycle-342b797480aa?source=rss-8c33eac83e14------2</link>
            <guid isPermaLink="false">https://medium.com/p/342b797480aa</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[app-life-cycle]]></category>
            <dc:creator><![CDATA[Raju Potharaju]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 06:15:44 GMT</pubDate>
            <atom:updated>2023-03-02T06:15:44.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_kIqPw1cv2fK-9vmLJGkQ.png" /><figcaption>Blog Banner</figcaption></figure><p>Flutter is a popular open-source framework for building cross-platform applications. When building apps with Flutter, it’s important to understand the app lifecycle. The app lifecycle defines the various states that an app can be in and the methods that are called as the app transitions between those states. Understanding the app lifecycle can help us create more efficient and responsive apps.</p><p>In this blog, we’ll explore the Flutter app lifecycle and provide examples of how to handle the various app states.</p><p>So Let&#39;s deep dive into the Flutter app life cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*p8oeTcstITkt44q1PkchmA.gif" /></figure><h3>The Flutter App Lifecycle</h3><p>The Flutter app lifecycle consists of four states:</p><ol><li>resumed</li><li>inactive</li><li>paused</li><li>detached</li></ol><p>Here’s a brief overview of each state:</p><ul><li>resumed: The app is in the <strong>foreground</strong> and is receiving user input.</li><li>inactive: The app is in the <strong>foreground</strong> but is not receiving user input. This state can occur, for example, when a phone call comes in or when the user switches to another app.</li><li>paused: The app is in the <strong>background</strong> and is not visible to the user. This state occurs when the user presses the home button or switches to another app.</li><li>detached: The app is <strong>not running at all.</strong> This state can occur, for example, when the app is terminated by the operating system or when the device is restarted.</li></ul><h3>Handling App Lifecycle Events</h3><p>Flutter provides several methods that are called app transitions between the different lifecycle states. These methods can be overridden to handle app lifecycle events. Here are the methods:</p><ul><li>didChangeAppLifecycleState: This method is called whenever the app transitions between lifecycle states. It receives an AppLifecycleState object that indicates the new state. You can use this method to perform actions when the app transitions between states.</li><li>dispose: This method is called when the app is about to be destroyed. You can use this method to clean up any resources that your app is using.</li></ul><p>Here are some examples of how to use these methods to handle app lifecycle events:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class AppLifeCycleExample extends StatefulWidget {<br>  const AppLifeCycleExample({super.key});<br><br>  @override<br>  _AppLifeCycleExampleState createState() =&gt; _AppLifeCycleExampleState();<br>}<br><br>class _AppLifeCycleExampleState extends State&lt;AppLifeCycleExample&gt;<br>    with WidgetsBindingObserver {<br>  AppLifecycleState? _appLifecycleState;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    WidgetsBinding.instance.addObserver(this);<br>  }<br><br>  @override<br>  void dispose() {<br>    WidgetsBinding.instance.removeObserver(this);<br>    super.dispose();<br>  }<br><br>  @override<br>  void didChangeAppLifecycleState(AppLifecycleState state) {<br>    super.didChangeAppLifecycleState(state);<br>    setState(() {<br>      _appLifecycleState = state;<br>      print(_appLifecycleState);<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: Scaffold(<br>        appBar: AppBar(<br>          title: const Text(&#39;App Lifecycle Example&#39;),<br>        ),<br>        body: Center(<br>          child: Text(<br>                  &#39;App is currently in $_appLifecycleState state.&#39;,<br>                  textAlign: TextAlign.center,<br>                  style: const TextStyle(fontSize: 20),<br>                ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>In this example, we’re using the didChangeAppLifecycleState method to update the app&#39;s state and also print the state in the command line whenever the app transitions between lifecycle states. We&#39;re also using the dispose method to remove the observer that we added in the initState method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*KZvuBq9KeKNAgzp-fzVz8A.png" /><figcaption>UI Example</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*kN7IX0S6o4WSeKwkXxbIBA.png" /><figcaption>Command Line Example</figcaption></figure><p>Hurray! we have learned about the Flutter app lifecycle in a very simple way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*0lzqGwAJ6K_xF6G7VVfJmA.gif" /></figure><h3>Conclusion</h3><p>Understanding the Flutter app lifecycle is important for creating efficient and responsive apps. By using the methods provided by Flutter, you can handle app lifecycle events and perform actions when the app transitions between states. Remember to use the dispose method to clean up any resources that your app is using when it&#39;s about to be destroyed. With this knowledge, you&#39;ll be well-equipped to create great Flutter apps that provide a seamless user experience.</p><p><em>Thank you for reading this article, if you learned something new from this blog do clap as many times as possible, it really motivates me to share all my learnings with the flutter community.</em></p><p><em>Connect with me on </em><a href="https://linkedin.com/in/rajupotharaju155"><em>LinkedIn</em></a><em> for more flutter-related content.</em></p><p><em>Image Credits: </em><a href="https://www.freepik.com/free-vector/new-functions-concept-illustration_13795573.htm#page=2&amp;query=flutter&amp;position=35&amp;from_view=search&amp;track=sph"><em>Image by storyset</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=342b797480aa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gytworkz/deep-dive-into-flutter-app-lifecycle-342b797480aa">Deep dive into Flutter App Lifecycle.</a> was originally published in <a href="https://medium.com/gytworkz">GYTWorkz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building responsive apps in Flutter]]></title>
            <link>https://medium.com/gytworkz/building-responsive-apps-in-flutter-65617da7e607?source=rss-8c33eac83e14------2</link>
            <guid isPermaLink="false">https://medium.com/p/65617da7e607</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[widget]]></category>
            <category><![CDATA[responsive-design]]></category>
            <dc:creator><![CDATA[Raju Potharaju]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 19:55:58 GMT</pubDate>
            <atom:updated>2023-03-01T19:55:58.832Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RueCXLhnQp_UJcO5AM1vig.png" /></figure><p>Flutter is a popular open-source mobile application development framework that allows us to build natively compiled apps for mobile, web, and desktop with a single codebase. Flutter provides various features and tools that make it easy for us to build responsive and attractive apps.</p><p>In this blog, we will discuss how to build responsive apps in Flutter with examples.</p><ol><li><strong>Use MediaQuery</strong></li></ol><p>Flutter provides MediaQuery, a class that retrieves the size and device pixel density of the screen. MediaQuery is useful for building responsive apps as it allows developers to adjust the app’s layout based on the device’s screen size.</p><p>For example, suppose you want to display a container that takes up 50% of the screen’s width on larger screens and 80% of the screen’s width on smaller screens. You can use MediaQuery to achieve this:</p><pre>Size screenSize = MediaQuery.of(context).size;<br>Container(<br>  width: screenSize.width &gt; 600 ? screenSize.width * 0.5 : screenSize.width * 0.8,<br>  height: 100,<br>  color: Colors.blue,<br>)</pre><p>In this example, the container’s width is set to 50% of the screen’s width if the screen’s width is greater than 600 pixels, and 80% of the screen’s width otherwise.</p><p><strong>2. Use Expanded and Flexible widgets</strong></p><p>Flutter provides two widgets, Expanded and Flexible, that allow developers to create flexible layouts that adjust to the available space.</p><p>The Expanded widget is used to expand a child widget to fill the available space in a Row or Column. For example, suppose you want to display three containers in a row, and you want the middle container to take up twice as much space as the other two containers. You can use Expanded to achieve this:</p><pre>Row(<br>  children: [<br>    Container(<br>      width: 50,<br>      height: 100,<br>      color: Colors.red,<br>    ),<br>    Expanded(<br>      child: Container(<br>        height: 100,<br>        color: Colors.green,<br>      ),<br>      flex: 2,<br>    ),<br>    Container(<br>      width: 50,<br>      height: 100,<br>      color: Colors.blue,<br>    ),<br>  ],<br>)</pre><p>In this example, the middle container is wrapped in an Expanded widget with a flex value of 2, which means it takes up twice as much space as the other two containers.</p><p>The Flexible widget is used to make a child widget flexible and allow it to shrink or grow to fit the available space. For example, suppose you want to display a text widget that wraps to the next line if it cannot fit on one line. You can use Flexible to achieve this:</p><pre>Row(<br>  children: [<br>    Flexible(<br>      child: Text(<br>        &quot;This is a long text that should wrap to the next line if it cannot fit on one line&quot;,<br>        style: TextStyle(fontSize: 16),<br>      ),<br>    ),<br>  ],<br>)</pre><p>In this example, the Text widget is wrapped in a Flexible widget, which allows it to shrink or grow to fit the available space.</p><p><strong>3. Use LayoutBuilder</strong></p><p>Flutter provides LayoutBuilder, a widget that passes its constraints to its child. LayoutBuilder is useful for building responsive layouts as it allows developers to adjust the layout based on the available space.</p><p>For example, suppose you want to display a text widget that changes its font size based on the available space. You can use LayoutBuilder to achieve this:</p><pre>LayoutBuilder(<br>  builder: (BuildContext context, BoxConstraints constraints) {<br>    return Text(<br>      &quot;This is some text&quot;,<br>      style: TextStyle(fontSize: constraints.maxWidth / 10),<br>    );<br>  },<br>)</pre><p>In this example, the font size of the Text widget is set to one-tenth of the maximum width of the available space.</p><h3><strong>Conclusion</strong></h3><p>In conclusion, building responsive apps in Flutter requires the use of various techniques and widgets. MediaQuery, Expanded, Flexible, and LayoutBuilder are just a few examples of the tools and features that Flutter provides to help us build responsive and attractive apps.</p><p>By using these tools and techniques, we can create apps that adjust to different screen sizes and orientations, providing a seamless experience for users across a range of devices.</p><p>It’s important to keep in mind that building responsive apps is not just about making the layout adjust to different screen sizes. We should also consider factors such as accessibility, user experience, and performance when building responsive apps.</p><p>With the right techniques and tools, building responsive apps in Flutter can be a straightforward and rewarding experience. Happy coding!</p><p><em>If you find this blog informative do give a clap below and follow me.</em></p><p><em>Connect with me on </em><a href="https://linkedin.com/in/rajupotharaju155"><em>LinkedIn</em></a><em> for more flutter related content.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65617da7e607" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gytworkz/building-responsive-apps-in-flutter-65617da7e607">Building responsive apps in Flutter</a> was originally published in <a href="https://medium.com/gytworkz">GYTWorkz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Flutter with APIs and external services]]></title>
            <link>https://medium.com/gytworkz/integrating-flutter-with-apis-and-external-services-e8a5efb9da67?source=rss-8c33eac83e14------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8a5efb9da67</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Raju Potharaju]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 06:39:14 GMT</pubDate>
            <atom:updated>2023-02-23T06:39:14.986Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTaaS9eEXcY60nSOG3KGow.png" /></figure><p>Flutter is a popular framework for building mobile applications that can run on multiple platforms. To make your Flutter app more powerful, you may want to integrate it with APIs and external services.</p><p>In this blog, we will discuss how to integrate Flutter with APIs and external services, and I will provide some examples to help you get started.</p><p><strong>What is an API?</strong></p><p>API stands for Application Programming Interface. An API is a set of protocols and tools for building software applications. It allows two different software applications to communicate with each other. APIs can be used to integrate different systems or to share data between different applications.</p><p>If you want to more about API <a href="https://medium.com/geekculture/a-beginners-guide-to-apis-9aa7b1b2e172">click here</a>.</p><p><strong>Why integrate Flutter with APIs and external services?</strong></p><p>Integrating Flutter with APIs and external services can provide many benefits, such as:</p><ul><li><strong>Improved functionality:</strong> You can add more features to your app by integrating with external services and APIs.</li><li><strong>Faster development:</strong> Integrating with APIs can save development time by allowing you to reuse existing functionality instead of building it from scratch.</li><li><strong>Better user experience:</strong> Integrating with external services can improve the user experience by providing more personalized content and functionality.</li><li><strong>Improved security:</strong> By integrating with secure APIs, you can ensure that your app and user data are protected.</li></ul><p><strong>How to integrate Flutter with APIs and external services?</strong></p><p>Integrating Flutter with APIs and external services is relatively straightforward. Here are the general steps:</p><ol><li><strong>Identify the APIs and external services you want to integrate with:</strong> Determine what APIs and external services your app needs to interact with to provide the desired functionality.</li><li><strong>Understand the API documentation:</strong> Understand the API documentation to determine what endpoints you need to use and what data you need to provide.</li><li><strong>Use a package to make API calls:</strong> There are many packages available for Flutter that can be used to make API calls, such as http, dio, and retrofit. Choose the package that best fits your needs.</li><li><strong>Parse the JSON response:</strong> APIs usually return data in JSON format, so you need to parse the JSON response to use the data in your app.</li><li><strong>Use the data in your app:</strong> Once you have the data from the API, you can use it in your app to provide the desired functionality.</li></ol><h3>Example 1: Integrating with OpenWeatherMap API</h3><p>In this example, we will integrate with the OpenWeatherMap API to display the current weather for a given location.</p><ol><li>Identify the API: <a href="https://openweathermap.org/api"><strong><em>OpenWeatherMap</em></strong></a> provides a free API for accessing weather data.</li><li>Understand the API documentation: The API documentation specifies that we need to make a GET request to the following endpoint to get the current weather for a given location: https://api.openweathermap.org/data/2.5/weather?q={city name}&amp;appid={API key}. We need to provide the city name and our API key as parameters.</li><li>Use the http package: We will use the <a href="https://pub.dev/packages/http"><strong><em>http</em></strong></a> package to make the API call. Here is an example code snippet:</li></ol><pre>import &#39;dart:convert&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br><br>Future&lt;WeatherData&gt; fetchWeatherData(String cityName) async {<br>  final response = await http.get(Uri.parse(<br>      &#39;https://api.openweathermap.org/data/2.5/weather?q=$cityName&amp;appid={API key}&#39;));<br>  if (response.statusCode == 200) {<br>    final jsonResponse = json.decode(response.body);<br>    return WeatherData.fromJson(jsonResponse);<br>  } else {<br>    throw Exception(&#39;Failed to load weather data&#39;);<br>  }<br>}</pre><pre>import &#39;package:intl/intl.dart&#39;;<br><br>class WeatherData {<br>  final String cityName;<br>  final double temperature;<br>  final String sunrise;<br>  final String sunset;<br><br>  WeatherData({<br>    required this.cityName,<br>    required this.temperature,<br>    required this.sunrise,<br>    required this.sunset,<br>  });<br><br>  factory WeatherData.fromJson(Map&lt;String, dynamic&gt; json) {<br>    final DateFormat formatter = DateFormat(&#39;dd MMM HH:mm&#39;);<br>    return WeatherData(<br>        cityName: json[&#39;name&#39;],<br>        temperature: (json[&#39;main&#39;][&#39;temp&#39;] - 273.15),<br>        sunrise: formatter.format(<br>            DateTime.fromMillisecondsSinceEpoch(json[&#39;sys&#39;][&#39;sunrise&#39;] * 1000)),<br>        sunset: formatter.format(<br>            DateTime.fromMillisecondsSinceEpoch(json[&#39;sys&#39;][&#39;sunset&#39;] * 1000)));<br>  }<br>}</pre><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:ui_app/api_services_blog/weather_model.dart&#39;;<br>import &#39;weather_api.dart&#39;;<br><br>class WeatherHome extends StatefulWidget {<br>  const WeatherHome({super.key});<br>  @override<br>  State&lt;WeatherHome&gt; createState() =&gt; _WeatherHomeState();<br>}<br><br>class _WeatherHomeState extends State&lt;WeatherHome&gt; {<br>  late String _cityName = &#39;&#39;;<br>  Future&lt;WeatherData&gt;? futureDate;<br>  <br>  void getWeatherData() {<br>    futureDate = fetchWeatherData(_cityName);<br>    setState(() {});<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Weather App&#39;),<br>      ),<br>      body: Padding(<br>        padding: const EdgeInsets.all(20.0),<br>        child: Column(<br>          children: [<br>            Container(<br>                child: Column(<br>              children: [<br>                TextField(<br>                  onChanged: (value) =&gt; _cityName = value.trim(),<br>                ),<br>                ElevatedButton(<br>                    onPressed: getWeatherData,<br>                    child: const Center(<br>                      child: Text(&quot;Submit&quot;),<br>                    )),<br>              ],<br>            )),<br>            Container(<br>                child: FutureBuilder&lt;WeatherData&gt;(<br>              future: futureDate,<br>              builder: (context, snapshot) {<br>                if (snapshot.hasData) {<br>                  return Column(<br>                    mainAxisAlignment: MainAxisAlignment.center,<br>                    children: [<br>                      ListTile(<br>                        leading: const Text(&#39;City Name&#39;),<br>                        trailing: Text(snapshot.data!.cityName),<br>                      ),<br>                      ListTile(<br>                        leading: const Text(&#39;Temperature&#39;),<br>                        trailing: Text(<br>                            &#39;${snapshot.data!.temperature.toStringAsFixed(1)} °C&#39;),<br>                      ),<br>                      ListTile(<br>                        leading: const Text(&#39;Sunrise&#39;),<br>                        trailing: Text(snapshot.data!.sunrise.toString()),<br>                      ),<br>                      ListTile(<br>                        leading: const Text(&#39;Sunset&#39;),<br>                        trailing: Text(snapshot.data!.sunset.toString()),<br>                      ),<br>                    ],<br>                  );<br>                } else if (snapshot.hasError) {<br>                  return const Text(&#39;Failed to load weather data&#39;);<br>                }<br>                return const CircularProgressIndicator();<br>              },<br>            ))<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*1K4Sqc4kgV2EeyGy9vGmFw.png" /><figcaption>Weather App</figcaption></figure><h3>Example 2: Integrating with Firebase Authentication</h3><p>In this example, we will integrate with Firebase Authentication to allow users to sign in to our app.</p><ol><li>Identify the external service: Firebase provides a set of services for building mobile and web applications, including Firebase Authentication.</li><li>Understand the documentation: The Firebase Authentication documentation specifies that we need to configure Firebase in our app and use the provided API to authenticate users.</li><li>Use the firebase_auth package: We will use the <a href="https://pub.dev/packages/firebase_auth"><strong><em>firebase_auth</em></strong></a> package to authenticate users. Here is an example code snippet:</li></ol><pre>import &#39;package:firebase_auth/firebase_auth.dart&#39;;<br><br>class Auth {<br>  final FirebaseAuth _auth = FirebaseAuth.instance;<br><br>  Future&lt;UserCredential&gt; signInWithEmailAndPassword(String email, String password) async {<br>    try {<br>      final UserCredential userCredential = await _auth.signInWithEmailAndPassword(<br>          email: email,<br>          password: password<br>      );<br>      return userCredential;<br>    } on FirebaseAuthException catch (e) {<br>      if (e.code == &#39;user-not-found&#39;) {<br>        print(&#39;No user found for that email.&#39;);<br>      } else if (e.code == &#39;wrong-password&#39;) {<br>        print(&#39;Wrong password provided for that user.&#39;);<br>      }<br>      throw e;<br>    }<br>  }<br>}</pre><p>4. Handle authentication errors: Firebase Authentication may return errors when authenticating users. We need to handle these errors and display appropriate messages to the user.</p><p>5. Use the authenticated user in your app: Once the user is authenticated, we can use their information in our app to provide personalised functionality.</p><h4>Conclusion</h4><p>Integrating Flutter with APIs and external services can provide many benefits, such as improved functionality, faster development, better user experience, and improved security. By following the general steps and using packages provided by the Flutter community, it is relatively straightforward to integrate Flutter with APIs and external services. The examples provided in this blog should help you get started.</p><p><em>If you find this blog informative do give a clap below and follow me.</em></p><p><em>Connect with me on </em><a href="https://linkedin.com/in/rajupotharaju155"><em>LinkedIn</em></a><em> for more flutter related content.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8a5efb9da67" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gytworkz/integrating-flutter-with-apis-and-external-services-e8a5efb9da67">Integrating Flutter with APIs and external services</a> was originally published in <a href="https://medium.com/gytworkz">GYTWorkz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State management techniques in Flutter.]]></title>
            <link>https://medium.com/gytworkz/state-management-techniques-in-flutter-c5280f6d94b0?source=rss-8c33eac83e14------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5280f6d94b0</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[inheritedwidget]]></category>
            <category><![CDATA[provider]]></category>
            <category><![CDATA[bloc]]></category>
            <dc:creator><![CDATA[Raju Potharaju]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 15:14:10 GMT</pubDate>
            <atom:updated>2023-02-20T15:14:10.149Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RwRG3C-rdO5PQdeF-SyZ8A.png" /></figure><p>Flutter being the popular open-source mobile application development framework that enables us to build high-performance, cross-platform mobile applications. One of the key challenges in building mobile applications is managing the state of the application.</p><p>But, first of all <strong><em>What is State Management?</em></strong></p><p><strong>State management</strong> refers to the process of storing and retrieving the data of the application in a way that ensures its consistency and availability throughout the application’s lifecycle.</p><p>In this blog post, we will explore some of the state management techniques in Flutter with examples.</p><ol><li><strong>InheritedWidget and InheritedModel</strong></li></ol><p>InheritedWidget and InheritedModel are two of the most popular and powerful state management techniques in Flutter. These widgets provide a way to pass data down the widget tree to child widgets without having to pass it explicitly to each widget. This is achieved by creating a hierarchy of widgets that can access a common data source.</p><p>Here’s an example of using InheritedWidget to manage the state of a counter:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class Counter extends InheritedWidget {<br>  final int count;<br>  final VoidCallback increment;<br><br>  const Counter(<br>      {required this.count, required this.increment, required Widget child})<br>      : super(child: child);<br><br>  static Counter of(BuildContext context) =&gt;<br>      context.dependOnInheritedWidgetOfExactType&lt;Counter&gt;()!;<br><br>  @override<br>  bool updateShouldNotify(Counter oldWidget) =&gt; count != oldWidget.count;<br>}<br><br>class CounterApp extends StatefulWidget {<br>  @override<br>  _CounterAppState createState() =&gt; _CounterAppState();<br>}<br><br>class _CounterAppState extends State&lt;CounterApp&gt; {<br>  int count = 0;<br><br>  void increment() {<br>    setState(() {<br>      Counter.of(context).count + 1;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Counter(<br>      count: count,<br>      increment: increment,<br>      child: Scaffold(<br>        appBar: AppBar(title: const Text(&#39;Counter App&#39;)),<br>        body: CounterDisplay(),<br>        floatingActionButton: FloatingActionButton(<br>          onPressed: () =&gt; increment(),<br>          child: const Icon(Icons.add),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>//child Widget -&gt; state is not passed directly<br>class CounterDisplay extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    final counter = Counter.of(context);<br>    return Center(<br>      child: Text(<br>        &#39;Count: ${counter.count}&#39;,<br>        style: const TextStyle(fontSize: 24),<br>      ),<br>    );<br>  }<br>}</pre><p>In this example, the Counter widget is an InheritedWidget that stores the count and the increment function. The CounterApp widget creates an instance of Counter and passes it down the widget tree to its child widgets. The CounterDisplay widget uses the Counter.of(context) method to access the count value from the Counter widget.</p><p><strong>2. Provider</strong></p><p>Provider is a third-party state management library that simplifies the process of state management in Flutter. It is built on top of the InheritedWidget and provides a simple way to manage the state of an application. Provider can be used to manage complex data structures and provides a way to update the data without having to rebuild the entire widget tree.</p><p>Here’s an example of using Provider to manage the state of a counter:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:provider/provider.dart&#39;;<br><br>class CounterModel extends ChangeNotifier {<br>  int _count = 0;<br>  int get count =&gt; _count;<br>  void increment() {<br>    _count++;<br>    notifyListeners();<br>  }<br>}<br><br>class CounterAppWithProvider extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return ChangeNotifierProvider&lt;CounterModel&gt;(<br>      create: (_) =&gt; CounterModel(),<br>      child: Scaffold(<br>        appBar: AppBar(title: const Text(&#39;Counter App&#39;)),<br>        body: CounterDisplay(),<br>        floatingActionButton: FloatingActionButton(<br>          onPressed: () =&gt;<br>              Provider.of&lt;CounterModel&gt;(context, listen: false).increment(),<br>          child: const Icon(Icons.add),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>class CounterDisplay extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    final counter = Provider.of&lt;CounterModel&gt;(context);<br>    return Center(<br>      child: Text(<br>        &#39;Count: ${counter.count}&#39;,<br>        style: const TextStyle(fontSize: 24),<br>      ),<br>    );<br>  }<br>}</pre><p>In this example, the CounterModel is a class that extends the ChangeNotifier class from the provider package. It stores the count value and provides an increment() method to update the count. The CounterApp widget creates an instance of CounterModel using the ChangeNotifierProvider widget and passes it down the widget tree. The CounterDisplay widget uses the Provider.of&lt;CounterModel&gt;(context) method to access the count value from the CounterModel.</p><p><strong>3. Bloc</strong></p><p>Bloc is another popular state management technique in Flutter that provides a way to separate the business logic of an application from the UI. Bloc stands for Business Logic Component and is built on top of the Stream and StreamController classes.</p><p>Here’s an example of using Bloc to manage the state of a counter:</p><pre>import &#39;dart:async&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br><br>abstract class CounterEvent {}<br><br>class IncrementEvent extends CounterEvent {<br>  int incrementBy;<br>  IncrementEvent({required this.incrementBy});<br>}<br><br>class CounterBloc {<br>  int _count = 0;<br>  final _counterController = StreamController&lt;int&gt;();<br>  Stream&lt;int&gt; get counterStream =&gt; _counterController.stream;<br><br>  void dispose() {<br>    _counterController.close();<br>  }<br><br>  void mapEventToState(CounterEvent event) {<br>    if (event is IncrementEvent) {<br>      _count += event.increment;<br>      _counterController.add(_count);<br>    }<br>  }<br>}<br><br>class CounterAppWithBloc extends StatelessWidget {<br>  final _counterBloc = CounterBloc();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Counter App&#39;)),<br>      body: StreamBuilder&lt;int&gt;(<br>        stream: _counterBloc.counterStream,<br>        builder: (context, snapshot) {<br>          if (!snapshot.hasData) {<br>            return const Center(<br>              child: CircularProgressIndicator(),<br>            );<br>          }<br>          return Center(<br>            child: Text(<br>              &#39;Count: ${snapshot.data}&#39;,<br>              style: const TextStyle(fontSize: 24),<br>            ),<br>          );<br>        },<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () =&gt;<br>            _counterBloc.mapEventToState(IncrementEvent(incrementBy: 6)),<br>        child: const Icon(Icons.add),<br>      ),<br>    );<br>  }<br>}</pre><p>In this example, the CounterBloc class manages the state of the counter and provides a counterStream to emit the updated count value. The CounterAppWithBloc widget creates an instance of CounterBloc and uses a StreamBuilder to listen to the counterStream and update the UI when the count value changes. The floatingActionButton calls the mapEventToState() method of the CounterBloc to update the count value.</p><p><strong>Conclusion</strong></p><p>State management is a critical aspect of mobile application development. In Flutter, there are several state management techniques that we as developers can use to manage the state of our applications. The choice of state management technique depends on the complexity of the application and the preferences of the developer. In this blog post, we have explored some of the most popular state management techniques in Flutter, including <strong>InheritedWidget, Provider, and Bloc, with examples</strong>.</p><p><em>If you find this blog informative do give a clap below and follow me.</em></p><p><em>Connect with me on </em><a href="https://linkedin.com/in/rajupotharaju155"><em>LinkedIn</em></a><em> for more flutter related content.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5280f6d94b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gytworkz/state-management-techniques-in-flutter-c5280f6d94b0">State management techniques in Flutter.</a> was originally published in <a href="https://medium.com/gytworkz">GYTWorkz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building beautiful UIs with Flutter.]]></title>
            <link>https://medium.com/gytworkz/building-beautiful-uis-with-flutter-b7fe7dbd4df5?source=rss-8c33eac83e14------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7fe7dbd4df5</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Raju Potharaju]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 07:09:54 GMT</pubDate>
            <atom:updated>2023-02-15T07:09:54.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UzKGm0Sp9uZR63iIcerJg.png" /><figcaption>Blog Banner</figcaption></figure><p>In today’s world, where mobile apps have become an essential part of our daily lives, it’s crucial to build visually appealing and engaging user interfaces (UIs) that captivate users’ attention. Flutter, a popular open-source mobile application development framework, provides developers with a vast array of tools and techniques to build beautiful UIs that stand out from the crowd.</p><p>In this blog, we’ll explore some of the best practices for building beautiful UIs in Flutter, along with some examples to help illustrate the concepts.</p><ol><li><strong>Use Flutter Widgets</strong></li></ol><p>Flutter comes with a plethora of built-in widgets that are designed to simplify the process of building beautiful UIs. Some of these include text fields, buttons, images, icons, and more. By using these widgets, developers can easily build functional and visually pleasing UIs without having to write any code from scratch.</p><p>For example, let’s say we want to create a button with a gradient background. We can use the Container widget to wrap the Text widget and set the decoration property of the container to a BoxDecoration object, which we can then customize to achieve the desired gradient effect. The result is a beautiful button that&#39;s easy to customize and modify.</p><pre>Container(<br>  decoration: BoxDecoration(<br>    gradient: LinearGradient(<br>      colors: [Colors.blue, Colors.green],<br>      begin: Alignment.topLeft,<br>      end: Alignment.bottomRight,<br>    ),<br>    borderRadius: BorderRadius.circular(5.0),<br>  ),<br>  child: Text(<br>    &#39;Click me!&#39;,<br>    style: TextStyle(color: Colors.white),<br>  ),<br>),</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*9g0cW1Qn4WdqOrbNKVQ7DA.png" /></figure><p><strong>2. Use Custom Widgets</strong></p><p>While Flutter provides a vast array of built-in widgets, sometimes developers need to create custom widgets to achieve a particular UI design. Custom widgets allow developers to encapsulate complex UI elements into reusable components that can be used throughout the application. This can greatly improve the efficiency of the development process and help ensure a consistent design throughout the app.</p><p>For example, let’s say we want to create a custom avatar widget that displays an image and some text underneath it. We can create a StatelessWidget that takes in the image and text as parameters and returns a Column widget containing the Image widget and a Text widget wrapped in a Padding widget to add some space between the two elements.</p><pre>class Avatar extends StatelessWidget {<br>  final String image;<br>  final String text;<br><br>  Avatar({this.image, this.text});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      children: [<br>        Image.asset(image),<br>        Padding(<br>          padding: EdgeInsets.only(top: 10.0),<br>          child: Text(text),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><p><strong>3. Use Material Design or Cupertino Style</strong></p><p>Flutter provides two main styles of UI design — Material Design and Cupertino. Material Design is a design language developed by Google and is widely used in Android applications. It focuses on using bold colors, typography, and grid-based layouts. Cupertino, on the other hand, is a design language developed by Apple and is used in iOS applications. It focuses on using translucent materials, thin lines, and subtle gradients.</p><p>For example, let’s say we want to create a login screen using Material Design. We can use the Scaffold widget to create a basic layout that includes an AppBar, a TextField widget for the username, and a TextField widget for the password. We can then use the RaisedButton widget to create a login button with a custom color and text.</p><pre>Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Login&#39;),<br>      ),<br>      body: Padding(<br>        padding: const EdgeInsets.all(20.0),<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.start,<br>          children: [<br>            const TextField(decoration: InputDecoration(hintText: &#39;Username&#39;)),<br>            const TextField(<br>              obscureText: true,<br>              decoration: InputDecoration(hintText: &#39;Password&#39;),<br>            ),<br>            const SizedBox(height: 20),<br>            ElevatedButton(<br>              child: const Text(&#39;Login&#39;),<br>              onPressed: () {},<br>            ),<br>          ],<br>        ),<br>      ),<br>    );</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*6V4MEHfKJbVJu41PhQWBBw.png" /></figure><p><strong>4. Use Animation and Motion</strong><br>Adding animation and motion to UI elements can greatly enhance the user experience and make the app feel more interactive and engaging. Flutter provides an extensive animation framework that allows developers to add animations to various UI elements such as buttons, images, and text fields.</p><p>For example, let’s say we want to add a simple animation to a button that makes it grow and shrink when clicked. We can use the `AnimatedContainer` widget to create a container that changes its size over a specified duration. We can then wrap the container in a `GestureDetector` widget and set the `onTap` property to a function that toggles a boolean variable to trigger the animation.</p><pre><br>class _AnimatedButtonState extends State&lt;AnimatedButton&gt; {<br>  bool _isTapped = false;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return GestureDetector(<br>      onTap: () {<br>        setState(() {<br>          _isTapped = !_isTapped;<br>        });<br>      },<br>      child: AnimatedContainer(<br>        duration: const Duration(milliseconds: 100),<br>        width: 200,<br>        height: 100,<br>        decoration: BoxDecoration(<br>          gradient: LinearGradient(<br>            colors: _isTapped<br>                ? [Colors.blue, Colors.green]<br>                : [Colors.yellow, Colors.red],<br>            begin: Alignment.topLeft,<br>            end: Alignment.bottomRight,<br>          ),<br>          borderRadius: BorderRadius.circular(5.0),<br>        ),<br>        child: const Center(<br>            child: Text(<br>          &#39;Click me!&#39;,<br>          style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),<br>        )),<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*3FJXEMhbcJYP0V31blWMIA.gif" /><figcaption>GIF: Shows Change in color on click</figcaption></figure><p>In conclusion, building beautiful UIs in Flutter is essential to creating engaging and visually appealing mobile applications. By using built-in widgets, creating custom widgets, using Material Design or Cupertino style, and adding animation and motion, we can create stunning UIs that stand out from the crowd. With the plethora of tools and techniques available in Flutter, the possibilities are endless, and we developers are only limited by our imagination.</p><p><em>If you find this blog informative do give a clap below.</em></p><p><em>Connect with me on </em><a href="https://linkedin.com/in/rajupotharaju155"><em>LinkedIn</em></a><em> for more flutter related content.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7fe7dbd4df5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gytworkz/building-beautiful-uis-with-flutter-b7fe7dbd4df5">Building beautiful UIs with Flutter.</a> was originally published in <a href="https://medium.com/gytworkz">GYTWorkz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>