<?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"><channel><title><![CDATA[CodingMountain's Blog]]></title><description><![CDATA[CodingMountain's Blog]]></description><link>https://blog.codingmountain.com</link><generator>RSS for Node</generator><lastBuildDate>Mon, 13 Apr 2026 11:37:54 GMT</lastBuildDate><atom:link href="https://blog.codingmountain.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Debouncing in Flutter]]></title><description><![CDATA[Look and analyze the code below. Did you find anything wrong or odd?
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Materia...]]></description><link>https://blog.codingmountain.com/debouncing-in-flutter</link><guid isPermaLink="true">https://blog.codingmountain.com/debouncing-in-flutter</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Dart]]></category><category><![CDATA[debouncing]]></category><category><![CDATA[debounce]]></category><category><![CDATA[Flutter App Development]]></category><dc:creator><![CDATA[Safal Shrestha]]></dc:creator><pubDate>Mon, 22 May 2023 12:11:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684388761049/d74fe6e2-28fa-48a9-8470-37d59c0ef781.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Look and analyze the code below. Did you find anything wrong or odd?</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;

<span class="hljs-keyword">void</span> main() =&gt; runApp(MyApp());

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> MaterialApp(
      title: <span class="hljs-string">'Flutter Demo'</span>,
      debugShowCheckedModeBanner: <span class="hljs-keyword">false</span>,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: <span class="hljs-keyword">const</span> MyHomePage(title: <span class="hljs-string">'Flutter Demo Home Page'</span>),
    );
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyHomePage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatefulWidget</span> </span>{
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">String</span> title;

  <span class="hljs-keyword">const</span> MyHomePage({
    Key? key,
    <span class="hljs-keyword">required</span> <span class="hljs-keyword">this</span>.title,
  }) : <span class="hljs-keyword">super</span>(key: key);

  <span class="hljs-meta">@override</span>
  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">_MyHomePageState</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">State</span>&lt;<span class="hljs-title">MyHomePage</span>&gt; </span>{
  <span class="hljs-built_in">int</span> _counter = <span class="hljs-number">0</span>;

  <span class="hljs-keyword">void</span> _incrementCounter() {   
    setState(() {
      _counter++;
    }); 
    <span class="hljs-keyword">var</span> snackBar = SnackBar(
      content: Text(<span class="hljs-string">'Yay! A Counter SnackBar! <span class="hljs-subst">$_counter</span>'</span>),
    );
     ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            <span class="hljs-keyword">const</span> Text(
              <span class="hljs-string">'You have pushed the button this many times:'</span>,
            ),
            Text(
              <span class="hljs-string">'<span class="hljs-subst">$_counter</span>'</span>,
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: <span class="hljs-string">'Increment'</span>,
        child: <span class="hljs-keyword">const</span> Icon(Icons.add),
      ),
    );
  }
}
</code></pre>
<p>If you look at the code, the code looks fine and seems to work fine as well. Now I want you to copy the code to <a target="_blank" href="https://dartpad.dev/?">dartpad</a> and run it. After that click the floating action button a single time, and then press the button 5 time continuously. Did you find anything odd?</p>
<p>If you click the button 5 times continuously, you would see something like this.</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*S2HFXOuKGbsUqYcbeA1nAw.gif" alt /></p>
<p>We can see that the snack bar keeps on showing even after a long time that we clicked. The snack bar persists even if we change the screen. If we clicked continuously, showSnackbar is sent to the event loop and they are executed no matter what. It is working as intended but it leads to a bad user experience. We want to make it so that only the last snack bar is shown leading to a better user experience.</p>
<p>Here, I am giving the example of a snack bar but what if I was calling API, it would be called multiple times. We want to make it so that if an action is performed one after another in a short interval of time, in this case tapping a button and showing the snack bar, the previous action is canceled and only the latest action is executed. So how to do so?</p>
<h4 id="heading-debouncing">Debouncing</h4>
<p>Debouncing is a technique used to avoid unnecessary processing by setting a delay before executing a function, so that if the function is called again within the delay, the previous function is canceled and the timer is reset again. The function is only executed once the delay timer has been completed without any new events occurring.</p>
<p>Here are some of the important of Debouncing:</p>
<ul>
<li><p>It avoids unnecessary processing.</p>
</li>
<li><p>It optimizes performance by reducing function invocations.</p>
</li>
<li><p>It helps to enhance user experience.</p>
</li>
<li><p>It helps to optimize network requests and traffic.</p>
</li>
<li><p>It prevents race-around conditions.</p>
</li>
</ul>
<p>So, let's implement debouncing in our Flutter app and see the result.</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'dart:async'</span>;

<span class="hljs-keyword">void</span> main() =&gt; runApp(MyApp());

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> MaterialApp(
      title: <span class="hljs-string">'Flutter Demo'</span>,
      debugShowCheckedModeBanner: <span class="hljs-keyword">false</span>,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: <span class="hljs-keyword">const</span> MyHomePage(title: <span class="hljs-string">'Flutter Demo Home Page'</span>),
    );
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyHomePage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatefulWidget</span> </span>{
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">String</span> title;

  <span class="hljs-keyword">const</span> MyHomePage({
    Key? key,
    <span class="hljs-keyword">required</span> <span class="hljs-keyword">this</span>.title,
  }) : <span class="hljs-keyword">super</span>(key: key);

  <span class="hljs-meta">@override</span>
  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">_MyHomePageState</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">State</span>&lt;<span class="hljs-title">MyHomePage</span>&gt; </span>{
  <span class="hljs-built_in">int</span> _counter = <span class="hljs-number">0</span>;

  <span class="hljs-keyword">final</span> _debouncer = Debouncer(milliseconds: <span class="hljs-number">500</span>);
  <span class="hljs-keyword">void</span> _incrementCounter() {

    setState(() {
      _counter++;
    }); 
       <span class="hljs-keyword">var</span> snackBar = SnackBar(
      content: Text(<span class="hljs-string">'Yay! A Counter SnackBar! <span class="hljs-subst">$_counter</span>'</span>),
    );
    _debouncer.run(() {
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    });
  }

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            <span class="hljs-keyword">const</span> Text(
              <span class="hljs-string">'You have pushed the button this many times:'</span>,
            ),
            Text(
              <span class="hljs-string">'<span class="hljs-subst">$_counter</span>'</span>,
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: <span class="hljs-string">'Increment'</span>,
        child: <span class="hljs-keyword">const</span> Icon(Icons.add),
      ),
    );
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Debouncer</span> </span>{
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">int</span> milliseconds;
  Timer? _timer;
  Debouncer({<span class="hljs-keyword">required</span> <span class="hljs-keyword">this</span>.milliseconds});
  <span class="hljs-keyword">void</span> run(VoidCallback action) {
    <span class="hljs-keyword">if</span> (_timer != <span class="hljs-keyword">null</span>) {
      _timer!.cancel();
    }
    _timer = Timer(<span class="hljs-built_in">Duration</span>(milliseconds: milliseconds), action);
  }
}
</code></pre>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*XBUeMt5CHmNQod0bO3OZsg.gif" alt /></p>
<p>It’s much better. We can only see the last snack bar. It is much better and user-friendly.</p>
<p>Now, how did we implement debouncing in our code? Let’s dive in.</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Debouncer</span> </span>{
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">int</span> milliseconds;
  Timer? _timer;
  Debouncer({<span class="hljs-keyword">required</span> <span class="hljs-keyword">this</span>.milliseconds});
  <span class="hljs-keyword">void</span> run(VoidCallback action) {
    <span class="hljs-keyword">if</span> (_timer != <span class="hljs-keyword">null</span>) {
      _timer!.cancel();
    }
    _timer = Timer(<span class="hljs-built_in">Duration</span>(milliseconds: milliseconds), action);
  }
}
</code></pre>
<p>Here we are defining a <code>Debouncer</code> class. The <code>Debouncer</code> class has two properties: <code>milliseconds</code> and <code>_timer</code>. The <code>_timer</code> property is an <code>Timer</code> object used to manage the delay.</p>
<pre><code class="lang-dart">_timer = Timer(<span class="hljs-built_in">Duration</span>(milliseconds: milliseconds), action);
</code></pre>
<p>The timer takes two parameters. The first param is the duration and the second params void callback or the function that is executed once the countdown/duration is completed. We can cancel the execution of the function at any time with <code>_timer!.cancel()</code>.</p>
<p>Now let's look at <code>run</code> function.</p>
<p>In this function, at first, we are checking if the <code>_timer</code> is null or not. At first, it is null as we haven’t initialized it. As the <code>_timer</code> is null,<code>_timer!.cancel()</code> doesn’t run for the first time. After that the timer function is initialized and the <code>action</code> function that we provided is set to run after the time we provide. Now let’s see what happens when we call the <code>run</code> function again. This time <code>_timer</code> isn’t null as it has been initialized before, so <code>_timer!.cancel()</code> gets executed canceling the previous function that was set to run. If our next call exceeds the delay we provided, the function gets called. After that the <code>_timer</code> value is set again, to run the function again after the delay we provided. This process is continued again and again resulting in debouncing.</p>
<pre><code class="lang-dart">_debouncer.run(() {
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    });
</code></pre>
<p>In our code, we are passing the function to show the snack bar so that even if the user starts button mashing, the function gets executed a single time within the specified duration or time frame.</p>
<blockquote>
<p>If you are still struggling to find a place to use debouncing. Use it in search.</p>
</blockquote>
<hr />
<blockquote>
<p><em>Curiosity ignites, satisfaction revives. Keep exploring, keep thriving. As the saying goes,“ Curiosity killed the cat, but satisfaction brought it back.”</em></p>
</blockquote>
<hr />
]]></content:encoded></item><item><title><![CDATA[Publish and upgrade your Flutter Package on pub.dev]]></title><description><![CDATA[You are developing your awesome flutter app implementation awesome functionalities and awesome widgets. Now you want to share that awesomeness with others.
How do you do so?
Of course. By publishing your own awesome widgets as a package.
But how do y...]]></description><link>https://blog.codingmountain.com/publish-and-upgrade-your-flutter-package-on-pubdev</link><guid isPermaLink="true">https://blog.codingmountain.com/publish-and-upgrade-your-flutter-package-on-pubdev</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Dart]]></category><category><![CDATA[package]]></category><category><![CDATA[CodingMountain]]></category><category><![CDATA[coding mountain ]]></category><dc:creator><![CDATA[Safal Shrestha]]></dc:creator><pubDate>Mon, 22 May 2023 12:08:55 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://cdn-images-1.medium.com/max/2706/1*aEMGm-70lA5NmVq_7tEamQ.png" alt /></p>
<p>You are developing your awesome flutter app implementation awesome functionalities and awesome widgets. Now you want to share that awesomeness with others.</p>
<h4 id="heading-how-do-you-do-so">How do you do so?</h4>
<p>Of course. By publishing your own awesome widgets as a package.</p>
<p>But how do you do so?</p>
<hr />
<p>In this article, I want to show how to create and publish a package in “<a target="_blank" href="http://pub.dev">pub.dev</a> ”.</p>
<p>First, pick a name for your package, mine will be <strong>hello_world</strong> which will return a container with the text “Hello World”. Then run</p>
<pre><code class="lang-plaintext">flutter create --template=package hello_world
</code></pre>
<p>in your terminal. It will create a template for your package in my case <strong>hello_world</strong>. In the template, you will find different files. Let’s look at some of them:</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*I1pJklNsv8mVDpiO0In9fw.png" alt /></p>
<ol>
<li><p><a target="_blank" href="http://CHANGELOG.md"><strong>CHANGELOG.md</strong></a><strong>:</strong> Here you will write the changes you made/added to the project. It is a record of changes for tracking your package and its version. It will appear in the changelog of your package.</p>
</li>
<li><p><strong>LICENSE:</strong> You can add your license here.</p>
</li>
<li><p><strong>pubspec.yaml:</strong> Your package dependencies go here.</p>
</li>
<li><p><a target="_blank" href="http://README.md"><strong>README.md</strong></a><strong>:</strong> It will appear in the Readme of your package. It can contain brief summary of your package along with documentation, example, installation, and so on.</p>
</li>
<li><p><strong>lib</strong>: It is where you will write your package</p>
</li>
</ol>
<p>Now let’s write the package.</p>
<p>Inside the lib, we will find <strong>hello_world.dart</strong>. Inside you will find the template.</p>
<pre><code class="lang-plaintext">library hello_world;

/// A Calculator.
class Calculator {
  /// Returns [value] plus 1.
  int addOne(int value) =&gt; value + 1;
}
</code></pre>
<blockquote>
<p>The <code>library</code> keyword is used to give the library a name, which can be used to reference it from other parts of the code.</p>
</blockquote>
<p>Let’s write our package.</p>
<pre><code class="lang-plaintext">library hello_world;

import 'package:flutter/material.dart';

class HelloWorld extends StatelessWidget {
  const HelloWorld({super.key});

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Text("Hello World!"),
    );
  }
}
</code></pre>
<p>Oh, and let’s initialize a Git repo in our project which helps when we need to publish our package.</p>
<p>Now we are ready to publish our package. Right?</p>
<p>Wrong. Before publishing the package, we still go something left to do. First, let’s organize our code.</p>
<p>We will create a new folder <strong>lib/src</strong> and put our implementation/widget there.</p>
<blockquote>
<p>You can have any folder structure, but it is recommended to use lib/src . [source](<a target="_blank" href="https://dart.dev/guides/libraries/create-library-packages">https://dart.dev/guides/libraries/create-library-packages</a>)</p>
</blockquote>
<p>After that, our project will look like this.</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*MIutgUxjfW68Gh390fnZBw.png" alt /></p>
<p>We have moved out implementation code to <strong>hello.dart</strong> inside <strong>src</strong>.</p>
<p>E.g., <strong>hello.dart</strong></p>
<pre><code class="lang-plaintext">import 'package:flutter/material.dart';

class HelloWorld extends StatelessWidget {
  const HelloWorld({super.key});

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Text("Hello World!"),
    );
  }
}
</code></pre>
<p><strong>hello_world.dart</strong> is used as a barrel file to export our implementation.</p>
<p>E.g., <strong>hello_world.dart</strong></p>
<pre><code class="lang-plaintext">library hello_world;

export "src/hello.dart";
</code></pre>
<blockquote>
<p>A barrel file is a way to integrate multiple exports from different files into a single export.</p>
</blockquote>
<p>Now our package is complete. Before publishing let’s add an example.</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*3QotqY5MNWRyIh9WMiph6Q.png" alt /></p>
<p>The example will contain a code from <strong>example/lib/main.dart.</strong> We haven’t yet created an example folder.</p>
<p>Let’s run the command:</p>
<pre><code class="lang-plaintext">flutter create example
</code></pre>
<p>After this, you will have a flutter project with a name example. Inside pubspec.yaml of example you can import your package in example with <strong>path: ../</strong> instead of version.</p>
<p>E.g. <strong>example/pubspec.yaml</strong></p>
<pre><code class="lang-plaintext">name: example
description: A new Flutter project.

publish_to: 'none'

version: 1.0.0+1

environment:
  sdk: '&gt;=2.18.5 &lt;3.0.0'

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  hello_world:
    path: ../

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^2.0.0

flutter:
  uses-material-design: true
</code></pre>
<p>Now my <strong>lib/main.dart</strong> will be</p>
<p>E.g <strong>lib/main.dart</strong></p>
<pre><code class="lang-plaintext">import 'package:flutter/material.dart';
import 'package:hello_world/hello_world.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'My Package'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}

class _MyHomePageState extends State&lt;MyHomePage&gt; {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: const HelloWorld(),
    );
  }
}
</code></pre>
<p>This will be displayed in the example section of <a target="_blank" href="http://pub.dev">pub.dev</a> of your package.</p>
<p>Now let’s change <a target="_blank" href="http://CHANGELOG.md">CHANGELOG.md</a></p>
<pre><code class="lang-plaintext">## 0.0.1

* Initial release of Hello World.
</code></pre>
<p>Now let’s write <a target="_blank" href="http://README.md">README.md</a></p>
<pre><code class="lang-plaintext"># Hello World
Gives Hello World widget

## Features
  - Hello world
  - Awesome
  - Null Safety

## Example Project
 Check the `example` folder
</code></pre>
<p>Now, let’s add a license to our package. You can use <a target="_blank" href="https://choosealicense.com/licenses/"><strong>this</strong></a> website to help you choose your license.</p>
<pre><code class="lang-plaintext">MIT License

Copyright (c) 2022 Safal Shrestha

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</code></pre>
<p>You can add the homepage and repository field to your pubspec.yaml .</p>
<p><img src="https://cdn-images-1.medium.com/max/2000/1*pYFfcD9vlME7NbEaDBzwUg.png" alt /></p>
<p>Now run</p>
<pre><code class="lang-plaintext">flutter pub publish --dry-run
</code></pre>
<p>This command will analyze our package and warns us if there is any error/issues in our packages. After that, you can publish your package to <a target="_blank" href="http://pub.dev">pub.dev</a> with the command:</p>
<pre><code class="lang-plaintext">flutter pub publish
</code></pre>
<p>Remember publishing is forever. After running the command, you will be asked to authenticate, and your package will be published after authenticating.</p>
<blockquote>
<p>If you want to upgrade your package. Increase your package version and run flutter pub publish again.</p>
</blockquote>
<hr />
<p>In this post, you learned how to publish and upgrade your package. If you have any problem, you can reference my package <a target="_blank" href="https://pub.dev/packages/focus_widget_list">here</a>.</p>
<p><strong>Thanks for reading!</strong></p>
]]></content:encoded></item><item><title><![CDATA[Understanding Flutter Widget Lifecycle for Effective App Development]]></title><description><![CDATA[In general terms, lifecycle represents the stage from its creation until its destruction. In the context of flutter, it's the same. Today we will discuss on Widget lifecycle (Don’t confuse it with the App lifecycle).
As a flutter developer how we sho...]]></description><link>https://blog.codingmountain.com/understanding-flutter-widget-lifecycle-for-effective-app-development</link><guid isPermaLink="true">https://blog.codingmountain.com/understanding-flutter-widget-lifecycle-for-effective-app-development</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[android development]]></category><dc:creator><![CDATA[Pawan Acharya]]></dc:creator><pubDate>Wed, 03 May 2023 11:49:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1683111865279/4fbf521f-a191-4000-8890-678378c3401b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In general terms, lifecycle represents the stage from its creation until its destruction. In the context of flutter, it's the same. Today we will discuss on <strong>Widget lifecycle</strong> (Don’t confuse it with the App lifecycle).</p>
<p><strong><em>As a flutter developer how we should utilize those lifecycle methods</em></strong> is the primary intent of this article so let’s move to the fun part.</p>
<hr />
<h3 id="heading-createstate"><strong>createState()</strong></h3>
<p>When we create a stateful widget in Flutter, the <code>createState</code> method is immediately called to return a state instance of the associated class.</p>
<p>This is essential because, in Flutter, everything is immutable (including stateful widgets). It is important to separate the mutability task and delegate it to the state class. This way, Flutter can make immutable classes look and work like mutable ones, and we can see all the changes in the UI.</p>
<p>This also has a performance benefit, as it is easier for Flutter to change a state variable and reflect the change in an optimized manner than to recreate the entire widget tree due to small changes.</p>
<pre><code class="lang-dart"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HomePage</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatefulWidget</span> </span>{
  <span class="hljs-meta">@override</span>
  _HomePageState createState() =&gt; <span class="hljs-keyword">new</span> _HomePageState();
}
</code></pre>
<h3 id="heading-initstate"><strong>initState()</strong></h3>
<p>This is the first method called after-state creation. And it is called **only once.<br />**This method can be used to:</p>
<ol>
<li><p>Initilaize late variables</p>
</li>
<li><p>Subscribe to stream etc</p>
</li>
</ol>
<pre><code class="lang-dart"><span class="hljs-meta">@override</span>
initState() {
  <span class="hljs-keyword">super</span>.initState();
  _controller=TextEditingController();
  myStream.listen((data) {});
}
</code></pre>
<h3 id="heading-didchangedependencies"><strong>didChangeDependencies</strong></h3>
<p>This method is called immediately after the <strong><em>initState()</em></strong> for the first time and later on when its dependency changes.</p>
<p><strong><em>So what exactly is its dependency?</em></strong><br />Let's say we use <strong>MediaQuery.of</strong> in a widget then we can say our widget depends <strong>on MediaQuery.</strong> So whenever <strong>MediaQuery</strong> updates this method gets triggered.</p>
<p>So we can say if our widget depends on <code>Inherited Widget</code> (media query, theme, providers, etc) and whenever those inherited widget push updates it will trigger this method.</p>
<p>After this <code>build()</code> method will be triggered so as a developer there are not many scenarios where we may have to use custom logic here but as per official documentation, it says</p>
<blockquote>
<p><em>to do some expensive work (e.g., network fetches) when their dependencies change and that work would be too expensive to do for every build.</em></p>
</blockquote>
<p>For eg: From your <code>Inherited Widget</code> you may receive some value and need to do some expensive operation based on that value and show it in UI. You may not want to do this in the build method so<code>didChangeDependencies</code> will be the perfect spot for this.</p>
<h3 id="heading-didupdatewidget"><strong>didUpdateWidget</strong></h3>
<p>Let's take an example to understand this. You have a <code>Container</code> which is of Red color and with a button tap you change it to Blue.</p>
<p>Here both the old and new object instances are of the same type <code>runtimeType</code> but the data is different so in this case this method gets triggered. It receives old widgets too <code>didUpdateWidget(Widget oldWidget)</code> .</p>
<pre><code class="lang-dart"><span class="hljs-meta">@override</span>
<span class="hljs-keyword">void</span> didUpdateWidget(Widget oldWidget) {
  <span class="hljs-keyword">if</span> (oldWidget.color != widget.color) {
  <span class="hljs-comment">/// <span class="markdown">Your logic</span></span>
  }
}
</code></pre>
<p>How can we utilize it?</p>
<ul>
<li><p>One possible scenario could be used in animation to transition between values.</p>
</li>
<li><p>Another could be a specific use case based on your app requirement, based on new widget value do some different tasks for eg: subscribe to a new stream and un-subscribe to an earlier stream.</p>
</li>
</ul>
<p>Since <code>build()</code> method will be called after this method so it's redundant to call <code>setState((){})</code> in this method.</p>
<h3 id="heading-build">build()</h3>
<p>This is the important method where, as a programmer, we need to return the widget that we want to show to the user.</p>
<p>Also, this method can get triggered multiple times so it’s <strong>not a good practice to perform expensive tasks</strong> inside this method.</p>
<blockquote>
<p><em>This method can potentially be called in every frame and should not have any side effects beyond building a widget.</em></p>
</blockquote>
<h3 id="heading-setstate">setState((){})</h3>
<p>setState((){}) is a method that takes a method as a parameter and internally calls <code>markNeedsBuild()</code> method to trigger a new build.</p>
<pre><code class="lang-dart"><span class="hljs-comment">/// <span class="markdown">Implementation of setState() in flutter </span></span>
<span class="hljs-meta">@protected</span>
<span class="hljs-keyword">void</span> setState(VoidCallback fn) {
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">Object?</span> result = fn() <span class="hljs-keyword">as</span> <span class="hljs-built_in">dynamic</span>;
  _element!.markNeedsBuild();
}
</code></pre>
<p>Here we can see the internal implementation of setState. It first runs the method that we passed and triggers <code>markNeedsBuild()</code> . We can derive another thing from this implementation code that</p>
<ul>
<li>we should not pass an async function to setState as internally it won’t wait for the future to resolve so we won’t see the desired UI reflection.</li>
</ul>
<p>So as a developer, we can use this method to notify Flutter that something has changed and please update the UI.</p>
<pre><code class="lang-dart">setState(() {
  <span class="hljs-comment">/// <span class="markdown">New State values</span></span>
  color=Colors.red;
});
</code></pre>
<h3 id="heading-dispose">dispose()</h3>
<p>dispose() method is called when the state object is removed. This is the last method to get triggered in the lifecycle.</p>
<p>So as a developer, we can:</p>
<ol>
<li><p>Unsubscribe to streams</p>
</li>
<li><p>Dispose of the controllers</p>
</li>
<li><p>Stop animations etc</p>
</li>
</ol>
<p>So these are the most common and must-know lifecycle methods in Flutter.</p>
<blockquote>
<p><em>Since</em> <strong><em>stateless widget</em></strong> <em>doesn’t have its own mutable state (obvious from name) some lifecycle methods eg</em> <code>initState</code> <em>,</em> <code>dispose</code> <em>etc are missing here.</em></p>
</blockquote>
<hr />
<p>Sources:<br /><a target="_blank" href="https://www.youtube.com/watch?v=_gIbneld-bw%EF%BF%BChttps://api.flutter.dev/index.html">https://www.youtube.com/watch?v=_gIbneld-bw<br />https://api.flutter.dev/index.html</a></p>
]]></content:encoded></item><item><title><![CDATA[What are Keys in Flutter?]]></title><description><![CDATA[Working with Flutter, many times we bump into something called keys. The key is a property possessed by almost all widgets in Flutter. However, it is not used a lot and therefore is often overlooked. Why do widgets have keys then? Is it of any signif...]]></description><link>https://blog.codingmountain.com/what-are-keys-in-flutter</link><guid isPermaLink="true">https://blog.codingmountain.com/what-are-keys-in-flutter</guid><category><![CDATA[Flutter]]></category><category><![CDATA[Flutter Examples]]></category><category><![CDATA[Flutter Widgets]]></category><category><![CDATA[Mobile Development]]></category><dc:creator><![CDATA[Samriddhi Karmacharya]]></dc:creator><pubDate>Tue, 04 Apr 2023 08:32:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680596511816/b9da73e9-dafe-4301-834c-45766c8bce44.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Working with Flutter, many times we bump into something called keys. The key is a property possessed by almost all widgets in Flutter. However, it is not used a lot and therefore is often overlooked. Why do widgets have keys then? Is it of any significance to us? Let's find out.</p>
<h2 id="heading-what-are-keys">What are keys?</h2>
<p>Flutter describes Keys as an identifier for Widget, Element, and SemanticNodes. But what does that mean? This simply means that keys are unique labels assigned to widgets so that they can be distinguished from other widgets. For cases when widgets change positions in the widget tree, keys essentially help preserve their states. This also means that keys mostly come in handy for stateful widgets rather than stateless ones.</p>
<h2 id="heading-when-to-use-them">When to use them?</h2>
<p>Keys can go almost everywhere in our code and they do not cause any harm. But placing keys when it isn't required only means that it is unnecessarily hogging up memory spaces. Therefore, one must be clear on when to use them as well.</p>
<p>Most cases do not require the need to work with keys. They are useful while adding, removing, or reordering a collection of widgets of the same type that hold some state and are at the same level in the widget tree. In the absence of keys, updating such a collection of widgets may not give the expected kind of results. We tend to use keys with children of widgets like ListViews or Stateful widgets whose data is constantly changing.</p>
<p>To further clarify, why we need keys when modifying a collection of widgets here is a simple example illustration. The example described below shows two color tiles that swap places at the click of a button.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:320/1*3XbdhaQ9_lPfILdViiipeQ.gif" alt="swapping tiles" class="image--center mx-auto" /></p>
<center><b>Figure 1: Swapping tiles example</b></center>

<p>The example is represented in two ways.</p>
<p><em>Firstly</em>, the color tiles widgets are stateless with the color property stored in the widget itself. When the FloatingActionButton is tapped the tiles properly swap their position as expected.</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:keys_example/value_key_example.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:random_color/random_color.dart'</span>;

<span class="hljs-keyword">void</span> main() {
  runApp(<span class="hljs-keyword">const</span> MyApp());
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> MyApp({<span class="hljs-keyword">super</span>.key});
  <span class="hljs-comment">// This widget is the root of your application.</span>
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> MaterialApp(
      title: <span class="hljs-string">'Flutter Demo'</span>,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:<span class="hljs-keyword">const</span> PositionTiles(),
    );
  }
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PositionTiles</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatefulWidget</span> </span>{
  <span class="hljs-keyword">const</span> PositionTiles({Key? key}) : <span class="hljs-keyword">super</span>(key: key);
  <span class="hljs-meta">@override</span>
  State&lt;PositionTiles&gt; createState() =&gt; _PositionTilesState();
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">_PositionTilesState</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">State</span>&lt;<span class="hljs-title">PositionTiles</span>&gt; </span>{
  <span class="hljs-built_in">List</span>&lt;Widget&gt; tiles = [];
  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> initState() {
    <span class="hljs-keyword">super</span>.initState();
    tiles = [ 
       StatelessColorTiles(),
        StatelessColorTiles(),
    ];
  }
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Scaffold(
      body: Center(child: Row(mainAxisAlignment:MainAxisAlignment.center,children: tiles,),),
      floatingActionButton: FloatingActionButton(child: Icon(Icons.sentiment_very_satisfied, ),onPressed: swapTiles,),
    );
  }
  <span class="hljs-keyword">void</span> swapTiles() {
    setState(() {
      tiles.insert(<span class="hljs-number">1</span>, tiles.removeAt(<span class="hljs-number">0</span>));
    });
  }
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StatelessColorTiles</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{

 Color myColor = RandomColor().randomColor();
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span>  Container(
      height: <span class="hljs-number">100</span>,
      width: <span class="hljs-number">100</span>,
      color: myColor,
    );
  }
}
</code></pre>
<p><em>Secondly,</em> we make the color tile widgets stateful and store the color property in the state. This time, when pressing the floating action button nothing seems to happen. For the tiles to swap places correctly we need to add a key parameter to the stateful widgets.</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:keys_example/value_key_example.dart'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'package:random_color/random_color.dart'</span>;

<span class="hljs-keyword">void</span> main() {
  runApp(<span class="hljs-keyword">const</span> MyApp());
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-keyword">const</span> MyApp({<span class="hljs-keyword">super</span>.key});
  <span class="hljs-comment">// This widget is the root of your application.</span>
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> MaterialApp(
      title: <span class="hljs-string">'Flutter Demo'</span>,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:<span class="hljs-keyword">const</span> PositionTiles(),
    );
  }
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PositionTiles</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatefulWidget</span> </span>{
  <span class="hljs-keyword">const</span> PositionTiles({Key? key}) : <span class="hljs-keyword">super</span>(key: key);
  <span class="hljs-meta">@override</span>
  State&lt;PositionTiles&gt; createState() =&gt; _PositionTilesState();
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">_PositionTilesState</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">State</span>&lt;<span class="hljs-title">PositionTiles</span>&gt; </span>{
  <span class="hljs-built_in">List</span>&lt;Widget&gt; tiles = [];
  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> initState() {
    <span class="hljs-keyword">super</span>.initState();
    tiles = [ 
        StatefulColorTiles(key: UniqueKey(),),
        StatefulColorTiles(key: UniqueKey(),),

    ];
  }
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Scaffold(
      body: Center(child: Row(mainAxisAlignment:MainAxisAlignment.center,children: tiles,),),
      floatingActionButton: FloatingActionButton(child: Icon(Icons.sentiment_very_satisfied, ),onPressed: swapTiles,),
    );
  }
  <span class="hljs-keyword">void</span> swapTiles() {
    setState(() {
      tiles.insert(<span class="hljs-number">1</span>, tiles.removeAt(<span class="hljs-number">0</span>));
    });
  }
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StatefulColorTiles</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatefulWidget</span> </span>{
  <span class="hljs-keyword">const</span> StatefulColorTiles({Key? key}) : <span class="hljs-keyword">super</span>(key: key);
  <span class="hljs-meta">@override</span>
  State&lt;StatefulColorTiles&gt; createState() =&gt; _StatefulColorTilesState();
}
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">_StatefulColorTilesState</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">State</span>&lt;<span class="hljs-title">StatefulColorTiles</span>&gt; </span>{
  <span class="hljs-keyword">late</span> Color myColor;
  <span class="hljs-meta">@override</span>
  <span class="hljs-keyword">void</span> initState() {
    <span class="hljs-keyword">super</span>.initState();
    RandomColor _randomColor = RandomColor();
    myColor = _randomColor.randomColor();
  }
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Container(
        height: <span class="hljs-number">100</span>,
        width: <span class="hljs-number">100</span>,
        color: myColor,
     );
  }
}
</code></pre>
<p>The example thus, shows that keys are required for modifying widgets only if they are stateful. Stateless widgets don't require them.</p>
<h2 id="heading-behind-the-scenes">Behind the scenes:</h2>
<p>We just looked at an example where using keys allowed us to achieve the expected behavior from our code. But why did keys make this possible? Let's find out.</p>
<p>When rendering widgets, flutter not only builds a widget tree but side by side its corresponding element tree as well. The element tree holds information about the widgets present in the widget tree and references to its children’s widgets. In the process of modifying and re-rendering, flutter looks up the element tree to see whether or not the element tree has changed, so that if in case the element hasn't been changed it can reuse the old one itself.</p>
<p>For the stateless example, each of the tile widgets has its corresponding tile element. Because the color property was saved in the widget itself, when swapping the tiles in the widget tree, the references in the element tree weren't affected as they were the tile element itself. This thereby accurately swapped the color tiles.</p>
<p>For the stateful example, each tile widget had its corresponding tile element along with an extra state property in the element tree. When swapping the tiles, the corresponding elements do not match because they hold the state property and the desired behavior isn't achieved. After adding the key parameter to the tiles, the element tree and the widget tree get updated with the key values. Now when we swap the tiles, the tile elements with the help of their key can find out their corresponding widgets in the widget tree and update their reference correctly resulting in the widgets correctly swapping places and updating their color when the button is pressed.</p>
<p>Hence, this is how keys work under the hood and are useful for modifying stateful widgets in a collection.</p>
<h2 id="heading-types-of-keys"><strong>Types of Keys:</strong></h2>
<p>Keys are broadly classified into two types:</p>
<ol>
<li><p>Local Keys</p>
</li>
<li><p>Global Keys</p>
</li>
</ol>
<h3 id="heading-local-keys">Local Keys :</h3>
<p>These must be unique amongst the elements with the same parent. Local keys can further be classified as follows:</p>
<p><strong>Value Key:</strong></p>
<p>Value key takes alphanumeric values. They are commonly used in a list of children where the value of each child is unique and constant.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:700/1*-fioksAvW553DFDTOvYFwQ.png" alt class="image--center mx-auto" /></p>
<center><b>Figure 2: Value Key example</b></center>

<p><strong>Object Key:</strong></p>
<p>Same as the value key with the only difference being that it takes in a class object that holds data.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:389/1*ucNX4wjeCtyFSk2GQnBCLg.png" alt class="image--center mx-auto" /></p>
<center><b>Figure 2: Object Key example</b></center>

<p><strong>Unique Key:</strong></p>
<p>A unique key is used to identify a widget’s child in cases where they do not have unique values or don't have values at all.</p>
<p><img src="https://miro.medium.com/v2/resize:fit:568/1*V5XjDNHFH19ZC8b16VeVPA.png" alt class="image--center mx-auto" /></p>
<center><b>Figure 2:Unique Key example</b></center>

<p><strong>Page Storage Key:</strong></p>
<p>This key is used to preserve the scroll location of a user in scrolling views so that it can be saved for later.</p>
<p>That is all for this article. Stay tuned to learn about global keys in my next blog.</p>
<p>Till then, Happy reading!!</p>
]]></content:encoded></item><item><title><![CDATA[AndroidManifest.xml : Overview]]></title><description><![CDATA[Beginners usually ignore or forget about the AndroidManifest.xml file but its role in app development is huge. In this blog, we will try to get to know this important AndroidManifest.xml file better.

First, let’s look at what is XML file.
XML stands...]]></description><link>https://blog.codingmountain.com/androidmanifestxml-overview</link><guid isPermaLink="true">https://blog.codingmountain.com/androidmanifestxml-overview</guid><category><![CDATA[android app development]]></category><category><![CDATA[Android]]></category><category><![CDATA[xml]]></category><category><![CDATA[Android Studio]]></category><category><![CDATA[AndroidManifest]]></category><dc:creator><![CDATA[Safal Shrestha]]></dc:creator><pubDate>Fri, 31 Mar 2023 07:36:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680242584014/2b132654-3702-4b6a-a274-2492df6e906f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Beginners usually ignore or forget about the AndroidManifest.xml file but its role in app development is huge. In this blog, we will try to get to know this important AndroidManifest.xml file better.</p>
<hr />
<p><strong>First, let’s look at what is XML file.</strong></p>
<p>XML stands for eXtensible Markup Language, and it is a markup language used to store and transport data. An XML file is a text file that contains structured data in the form of tags and attributes. It is designed to be both human-readable and machine-readable, making it a popular choice for data exchange and storage. It doesn’t contain any code.</p>
<blockquote>
<p>Remember XML File Does Not DO Anything</p>
</blockquote>
<p>If an XML file doesn’t do anything, <strong>why are we even discussing it?</strong></p>
<p>Yes, XML alone doesn’t do anything in itself but it contains essential information about our app to the Android build tools, Android OS, and Google Play. It acts as the container of information for our build tools to use. It acts like a notebook which is used by the system to build and give information about our app.</p>
<p>As the information is used to build our app, it is crucial to be able to read, write and manipulate this information to step up our app development journey.</p>
<hr />
<p>AndroidManifest.xml is a required file in the android application at the root of the project source set. Every app project must have an AndroidManifest.xml file at the root of the project <a target="_blank" href="https://developer.android.com/studio/build#sourcesets">source set</a>.</p>
<p>The manifest file can be used to do a ton of things. Some of the basic and most important things the manifest file does are:</p>
<ol>
<li><strong>Describes the components of the application</strong></li>
</ol>
<p>Every app component that we create must be declared in the manifest file otherwise our app won’t recognize that app component and we will be unable to use those app components. App components include <strong>Activity, Service, BroadcastReceiver,</strong> and <strong>ContentProvider</strong>. Each app component has a specific tag assigned to it. <strong>&lt;activity&gt;</strong>, <strong>&lt;service&gt;</strong>,<strong>&lt;receiver&gt;</strong> and <strong>&lt;provider&gt;</strong> tags are assigned for <strong>Activity</strong>, <strong>Service</strong>, <strong>BroadcastReceiver,</strong> and <strong>ContentProvider</strong> respectively.</p>
<p><strong>2. Declares the Permissions</strong></p>
<p>The app requires permission from the system for some of its features. For example, if the app requires internet access to work properly, it must be declared in the manifest file. Android system has a unique label for each feature for the app to ask permission for.</p>
<p><strong>3. Device Compatibility</strong></p>
<p>In the app manifest, the feature required by the app to function properly is declared and thus only the system having those features available may install the app, thus describing if the app is compatible with the android system or not.</p>
<hr />
<h4 id="heading-structure-of-the-manifest">Structure of the manifest</h4>
<pre><code class="lang-plaintext">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest &gt;
    &lt;uses-sdk/&gt;
    &lt;uses-permission /&gt;
    &lt;application&gt;
       &lt;activity&gt;
          &lt;intent-filter&gt;
            &lt;action /&gt;
            &lt;category /&gt;
            &lt;data /&gt;
          &lt;/intent-filter&gt;
          &lt;meta-data /&gt;
        &lt;/activity&gt;
        &lt;service&gt;
            &lt;intent-filter&gt; . . . &lt;/intent-filter&gt;
            &lt;meta-data/&gt;
        &lt;/service&gt;
        &lt;receiver&gt;
            &lt;intent-filter&gt; . . . &lt;/intent-filter&gt;
            &lt;meta-data /&gt;
        &lt;/receiver&gt;
        &lt;provider&gt;
            &lt;grant-uri-permission /&gt;
            &lt;meta-data /&gt;
            &lt;path-permission /&gt;
        &lt;/provider&gt;
    &lt;/application&gt;
&lt;/manifest&gt;
</code></pre>
<p><strong>Sample</strong></p>
<pre><code class="lang-plaintext">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp"&gt;
    &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;
    &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
    &lt;uses-permission android:name="android.permission.VIBRATE" /&gt;
    &lt;uses-permission android:name="android.permission.FOREGROUND_SERVICE" /&gt;
    &lt;application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"&gt;
        &lt;activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.MyVpnApp"&gt;
            &lt;intent-filter&gt;
                &lt;action android:name="android.intent.action.MAIN" /&gt;
                &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;
          &lt;service android:name=".service.MyFirebaseMessagingService"
            android:exported="false"&gt;
            &lt;intent-filter&gt;
                &lt;action android:name="com.google.firebase.MESSAGING_EVENT" /&gt;
            &lt;/intent-filter&gt;
        &lt;/service&gt;
        &lt;receiver android:name=".ConnectionReceiver" &gt;
             &lt;intent-filter&gt;
                 &lt;action android:name="android.net.conn.CONNECTIVITY_CHANGE" /&gt;
               &lt;/intent-filter&gt;
        &lt;/receiver&gt;
    &lt;/application&gt;
&lt;/manifest&gt;
</code></pre>
<p>Let’s look at some of the tags and attributes of the manifest file:</p>
<p>1 . <strong>&lt;manifest&gt;</strong></p>
<p>It is the root element of the manifest file. It must contain <strong>&lt;application&gt;</strong> tag element and specify <code>xmlns:android</code> and <code>package</code> attributes.</p>
<p><strong>Attributes</strong></p>
<ul>
<li><p><code>xmlns:android</code> : This attribute should always be set to “<a target="_blank" href="http://schemas.android.com/apk/res/android">http://schemas.android.com/apk/res/android</a>". When using prefixes in XML, a namespace for the prefix must be defined. Instead of calling <code>android:id</code> , the xml will use ‘<a target="_blank" href="http://schemas.android.com/apk/res/android:id">http://schemas.android.com/apk/res/android:id</a> ’( it’s a URI Uniform Resource Identifier ) to be unique.</p>
</li>
<li><p><code>package</code> : It is the unique name for the app. It has to be formatted as a full Java-language-style package name.</p>
</li>
<li><p><code>android:installLocation</code> : It is used to define the default install location for the app. It can have three values, “internal only”, “auto” and “preferExternal”.</p>
</li>
</ul>
<ol>
<li><strong>&lt;application&gt;</strong></li>
</ol>
<p>It is used to define the properties and components of an Android application. It declares the application. The components of the app are declared in it.</p>
<p><strong>Attributes</strong></p>
<ul>
<li><p><code>android:label</code> : It is a user-readable label/name for the app as a whole.</p>
</li>
<li><p><code>android:icon</code> : It defines the icon for the app as a whole.</p>
</li>
<li><p><code>android:name</code> : It points to the subclass of the Application class that we created. The subclass is optional, most applications won’t need one. When an application starts, this class is instantiated before any other application component.</p>
</li>
</ul>
<ol>
<li><strong>&lt;uses-permission&gt;</strong></li>
</ol>
<p>It specifies the system permission that the user must grant for the app to function correctly.</p>
<p><strong>Attributes</strong></p>
<ul>
<li><code>android:name</code> : It is the name of the permission being requested. For example “android.permission.INTERNET” to use the internet.</li>
</ul>
<ol>
<li><strong>&lt;activity&gt;</strong></li>
</ol>
<p>It is used to define the activity that we have created. Activity can’t be recognized by the system if it is not defined under this tag. It can contain &lt;intent-filter&gt; ,&lt;meta-data&gt; and &lt;layout&gt;</p>
<p><strong>Attributes</strong></p>
<ul>
<li><p><code>android:name</code> : It points to the subclass of the Activity class that we created.</p>
</li>
<li><p><code>android:exported</code> : It contains a boolean value. If “true”, the activity is accessible to any app and is launchable by its exact class name. If “false”, it can only be launched by components of the same application.</p>
</li>
<li><p><code>android:theme</code> : It is a reference to the style resources for the activity to use.</p>
</li>
<li><p><code>android:configChanges</code> : It contains a list of configuration changes that the activity will handle. It prevents the activity from restarting when the defined config change takes place as the activity is restarted by default on configuration changes.</p>
</li>
<li><p><code>android:launchMode</code> : It instructs how the activity should be launched. It has 5 modes. They are:<code>“standard</code>","<code>singleTop</code>", "<code>singleTask</code>", "<code>singleInstance</code>", and "<code>singleInstancePerTask</code>".</p>
</li>
</ul>
<ol>
<li><strong>&lt;service&gt;</strong></li>
</ol>
<p>It is used to declare a Service subclass. All services must be declared by this tag. It can contain <code>\&lt;intent-filter&gt;</code> and <code>\&lt;meta-data&gt;</code>. Service run on background independent of any user interface.</p>
<p>Attributes</p>
<ul>
<li><code>android:name</code> : It points to the subclass of the Service class that we created.</li>
</ul>
<ol>
<li><strong>&lt;receiver&gt;</strong></li>
</ol>
<p>It declares the BroadcastReceiver subclass. Broadcast receivers enable applications to receive intents that are broadcast by the system or by other applications, even when other components of the application are not running.</p>
<ul>
<li><code>android:name</code> : It points to the subclass of BroadcastReceiver class that we created.</li>
</ul>
<ol>
<li><strong>&lt;provider&gt;</strong></li>
</ol>
<p>It contains a reference to the subclass of ContentProvider subclass. ContentProvider is necessary if we require to share data between multiple apps.</p>
<p><strong>Attributes</strong></p>
<ul>
<li><p><code>android:authorities</code> : It is the list of the URI that can be used to share data across the application. Multiple authorities are listed by separating their names with a semicolon.</p>
</li>
<li><p><code>android:name</code> : It points to the subclass of ContentProvider class that we created.</p>
</li>
<li><p><code>android:permission</code> : It is the permission that the app must have to use it.</p>
</li>
</ul>
<ol>
<li><strong>&lt;intent-filter&gt;</strong></li>
</ol>
<p>It informs the system about the intent that the app components can respond to. It opens the component receiving intent. It must contain <code>\&lt;action&gt;</code>and may contain <code>[\&lt;category&gt;](</code><a target="_blank" href="https://developer.android.com/guide/topics/manifest/category-element"><code>https://developer.android.com/guide/topics/manifest/category-element)</code>and<code>[\&lt;data&gt;](https://developer.android.com/guide/topics/manifest/data-element)</code></a>and<a target="_blank" href="https://developer.android.com/guide/topics/manifest/data-element">\<data></data></a>)<code>.</code></p>
<p>An Intent is a message or a request for the app component to perform some action. An app can have multiple intent filters.</p>
<ol>
<li><strong>&lt;action&gt;</strong></li>
</ol>
<p>It is the action that the app components can perform and is contained inside <code>\&lt;intent-filter&gt;</code> . For example,<strong>&lt;action android:name=”android.intent.action.SEND” /&gt;</strong> to send data to another application.</p>
<p><strong>Attribute</strong></p>
<ul>
<li><code>android:name</code> : It is the name of the action to be performed.</li>
</ul>
<ol>
<li><strong>&lt;category&gt;</strong></li>
</ol>
<p>It provides additional information on which the app components can perform an action. For example, the <strong>&lt;category android:name=”android.intent.category.LAUNCHER” /&gt;</strong> indicates that an activity should be listed in the launcher as an entry point for the application while first opening the app.</p>
<p><strong>Attribute</strong></p>
<ul>
<li><code>android:name</code> : It is the name of the category.</li>
</ul>
<blockquote>
<p>There are many other amazing tags and attributes for your need. I only explore the surface. For more detail and to find the tag that you need head over to the <a target="_blank" href="https://developer.android.com/guide/topics/manifest/manifest-intro"><strong>android official site</strong></a> <strong>.</strong></p>
</blockquote>
<hr />
<blockquote>
<h1 id="heading-thanks-for-reading"><strong>Thanks for reading</strong></h1>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[How to implement percent in gradient bar in React]]></title><description><![CDATA[In this article, we'll be creating a gradient bar that will show the percentage in React. There might be many packages that will be helpful in this scenario but the fun is when you can make it work from scratch. So let's begin.
Here is the demo link....]]></description><link>https://blog.codingmountain.com/how-to-implement-percent-in-gradient-bar-in-react</link><guid isPermaLink="true">https://blog.codingmountain.com/how-to-implement-percent-in-gradient-bar-in-react</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[SaugatRai]]></dc:creator><pubDate>Thu, 30 Mar 2023 10:12:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680171016284/9890aa8e-024b-4789-88f5-f4d84fa42051.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we'll be creating a gradient bar that will show the percentage in React. There might be many packages that will be helpful in this scenario but the fun is when you can make it work from scratch. So let's begin.</p>
<p>Here is the <a target="_blank" href="https://codesandbox.io/s/gradient-percent-bar-548d39">demo</a> link.</p>
<h3 id="heading-challenge">Challenge</h3>
<p>Creating a bar is easy unless there are no segments. But since we are creating a segmented bar, we need to take care of segments beforehand.</p>
<p>For this, we need a variable to store the number of segments. Let's say</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> BAR_COUNT = <span class="hljs-number">7</span>;
</code></pre>
<p>We are assuming there will be 7 segments of the bar but you can make more segments. The only constraint here is the color of each segment because for now, the 7 colors are hard-coded.</p>
<h3 id="heading-initialization">Initialization</h3>
<p>So a full bar is 100%. But since we have segments we also have to know how much percent will a segment hold. To determine this we can divide 100% by the total number of segments.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> quartilePercentage = <span class="hljs-number">100</span> / BAR_COUNT;
</code></pre>
<p>Since we have 7 segments, the percentage each bar will hold is 14.28%</p>
<p><em>100 / 7 = 14.28</em></p>
<p>This percentage will be handy when filling the bar with color later.</p>
<p>And since we need an actual percentage to show on the bar, we will pass them as props.</p>
<pre><code class="lang-typescript">&lt;GradientPercentBar percent={<span class="hljs-number">40</span>} /&gt;
</code></pre>
<p>We will use this percentage and assign it to a variable inside the component which will restrict the percentage to be maximum of 100.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> truePercent = percent &gt; <span class="hljs-number">100</span> ? <span class="hljs-number">100</span> : percent &lt; <span class="hljs-number">0</span> ? <span class="hljs-number">0</span> : percent;
</code></pre>
<p>We will also want to know where the percentage will fall and based on that we will assign a color. To figure out whether the label will be low, medium or high, we will divide the <code>truePercent</code> with the <code>quartilePercentage</code> we initialize earlier.</p>
<p><em>If truePercent = 40, the barIndicator will be 40/14.28 = 2.80 ~ 3.</em></p>
<p>Thus the <code>potentialLabel</code> is <strong>medium</strong>. So the bar will fall on 3rd segment</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> barIndicator = <span class="hljs-built_in">Math</span>.round(truePercent / quartilePercentage);

<span class="hljs-keyword">const</span> potentialLabel = barIndicator &lt; <span class="hljs-number">3</span> ? <span class="hljs-string">'low'</span> : barIndicator &lt;= <span class="hljs-number">5</span> ? <span class="hljs-string">'medium'</span> : <span class="hljs-string">'high'</span>;
</code></pre>
<h3 id="heading-indicator">Indicator</h3>
<p>We will create a simple indicator that will render the true percentage and the class will depend on the <code>potentialLabel</code>. We will get back to this function in a while.</p>
<pre><code class="lang-typescript">  <span class="hljs-keyword">const</span> renderTooltip = useCallback(
    <span class="hljs-function">(<span class="hljs-params">potential: <span class="hljs-built_in">string</span></span>) =&gt;</span> {
      <span class="hljs-keyword">return</span> (
        &lt;div className={<span class="hljs-string">`indicator <span class="hljs-subst">${potential}</span>`</span>}&gt;
          &lt;span&gt;{truePercent}&lt;/span&gt;
        &lt;/div&gt;
      );
    },
    [truePercent]
  );
</code></pre>
<h3 id="heading-magic-function">Magic Function</h3>
<p>This function will be responsible for creating the bar hence the magic function.</p>
<p>Some variables initialization that we will be needing later.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> elementArr = [];
<span class="hljs-keyword">let</span> root = <span class="hljs-built_in">document</span>.documentElement;
<span class="hljs-keyword">let</span> percent;
<span class="hljs-keyword">let</span> quartileValue;
</code></pre>
<p>We will now loop through <code>BAR_COUNT</code> with starting index of 1 and with each iteration, we will assign the range of each bar.</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">const</span> currentPoint = <span class="hljs-built_in">Math</span>.round(quartilePercentage * i);
</code></pre>
<p>This will provide us with the value each bar will have. For example</p>
<blockquote>
<p>In 1st iteration, i = 1 and (1 * 14.28) ~= 14</p>
<p>In 2nd iteration, i =2 and (2* 14.28) ~= 29</p>
<p>..</p>
<p>..</p>
<p>In 7th iteration, i = 7 and (7 * 14.28) ~= 100</p>
</blockquote>
<p>In this example, we have our <code>truePercent</code> value of 40, so all the bars below 40 should be filled. This will be done by pushing the element <code>elementArr</code> array.</p>
<pre><code class="lang-typescript">elementArr.push(&lt;div className=<span class="hljs-string">'item filled'</span> key={i} /&gt;);
</code></pre>
<p>But all the points above will have further calculations to determine what elements to push in <code>elementArr</code><strong>.</strong></p>
<p>Now we calculate the percentage that will be used to fill the bar with gradient color. If you are not familiar with CSS, we can use <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/background-image">background-image</a> to generate a linear effect to show half filled and half-empty.</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">const</span> previousPoint = <span class="hljs-built_in">Math</span>.round(quartilePercentage * (i - <span class="hljs-number">1</span>));

 <span class="hljs-keyword">const</span> difference = currentPoint - previousPoint;

 percent = <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">Math</span>.round(((truePercent - previousPoint) / difference) * <span class="hljs-number">100</span>)}</span>%`</span>;
</code></pre>
<p>We know that the <code>truePercent</code> lies in 3rd segment. But it will not fill to 3rd segment. Some of them will be half empty. Thus the above calculation comes in handy.</p>
<p>The above percentage will be</p>
<blockquote>
<p>((40- 29)/14) * 100 = 78.57 ~= 79</p>
</blockquote>
<p>This means the color will be filled up to 79% of 3rd segment and the rest will be white.</p>
<p>Now we have all the values required to implement the bar, we just need to push it into <code>elementArr</code><strong>.</strong></p>
<pre><code class="lang-typescript"> elementArr.push(
        &lt;div className={<span class="hljs-string">`item <span class="hljs-subst">${i === quartileValue ? <span class="hljs-string">'current filled'</span>               : <span class="hljs-string">''</span>}</span>`</span>} key={i}&gt;
            {i === quartileValue &amp;&amp; renderTooltip(potentialLabel)}
          &lt;/div&gt;
 );
</code></pre>
<p>After all the iterations, the elements will be pushed into <code>elementArr</code><strong>.</strong></p>
<p>Some code looks like this.</p>
<pre><code class="lang-typescript">root.style.setProperty(<span class="hljs-string">`--block-<span class="hljs-subst">${i}</span>`</span>, percent);
root.style.setProperty(<span class="hljs-string">`--left-value`</span>, percent);
</code></pre>
<p>These are used to set CSS variables that will be used CSS.</p>
<p>The <code>--block-${i}</code> is used in linear gradient while the <code>--left-value</code> is used to indicate how far the indicator is from the block.</p>
<h3 id="heading-final-structure">Final Structure</h3>
<p>The return function for the bar component is simple. It will call <code>rangeArray</code> function which will be responsible for generating the bar.</p>
<pre><code class="lang-typescript">    &lt;div className=<span class="hljs-string">'App'</span>&gt;
      &lt;div className=<span class="hljs-string">'potential__range'</span>&gt;
        &lt;div className=<span class="hljs-string">'range'</span>&gt;{rangeArray}&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
</code></pre>
<p>There is further CSS required to color the bar but the major functionality for the bar is done.</p>
<p>Hope this tutorial will be useful for some of you.</p>
]]></content:encoded></item></channel></rss>