<?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 Sumit Ghosh on Medium]]></title>
        <description><![CDATA[Stories by Sumit Ghosh on Medium]]></description>
        <link>https://medium.com/@sumit.ghoshqa?source=rss-452a6b29d9ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZHxEEqGBHLj-TIA71_p25w.jpeg</url>
            <title>Stories by Sumit Ghosh on Medium</title>
            <link>https://medium.com/@sumit.ghoshqa?source=rss-452a6b29d9ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:23:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sumit.ghoshqa/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[Understanding RouteObserver in Flutter]]></title>
            <link>https://medium.com/better-programming/understanding-routeobserver-in-flutter-309ce2997c27?source=rss-452a6b29d9ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/309ce2997c27</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Sumit Ghosh]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 07:50:05 GMT</pubDate>
            <atom:updated>2023-02-14T07:50:05.029Z</atom:updated>
            <content:encoded><![CDATA[<p>How to listen to Page transition events in flutter?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UHDwlVbYw0lWjNG3Knqj1A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@foxxmd">Matt Duncan</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>The RouteObserver in Flutter allows you to listen to page transition events. This is its sole purpose. In cases where you need to perform some action when a page is pushed or popped, the RouteObserver can be useful.</p><blockquote>A <em>Navigator</em>observer that notifies <em>RouteAwares</em> of changes to the state of their <em>Route</em>. RouteObserver informs subscribers whenever a route of type R is pushed on top of their own route of type R or popped from it.<br> — Flutter Documentation</blockquote><p><strong>What you will learn in the post?</strong></p><ul><li>How to listen to the page transition event in the RouteAware routes?</li><li>Understanding different classes (<em>RouteObserver</em> , <em>RouteAwares</em>, <em>Route</em>,) associated with it.</li><li>How to listen to page transition events Globally in the App?</li></ul><p>We will jump into the code directly and in 5 simple steps we will make a route and listen to the transition events.</p><ol><li>Initializing the <em>RouteObserver ,</em></li></ol><pre>class ObserverUtils {<br>  static final RouteObserver&lt;ModalRoute&gt; routeObserver =<br>      RouteObserver&lt;ModalRoute&gt;();<br>}</pre><p>2. Provide this observer to the <em>MaterialApp</em>,</p><pre>@override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      navigatorObservers: [ObserverUtils.routeObserver],<br>    );<br>  }</pre><p>3. Make your page “<em>RouteAware</em>”<em>,</em></p><pre>class MyHomePage extends StatefulWidget { ... }<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; with RouteAware { ... }</pre><p>4. Subscribe to the <em>RouteObserver ,</em></p><pre>@override<br>void didChangeDependencies() {<br>  super.didChangeDependencies();<br>  ObserverUtils.routeObserver.subscribe(this, ModalRoute.of(context)!);<br>}</pre><p>Here, we subscribe to the RouteObserver, noting that it has two parameters. The first one is RouteAware, where we pass “this” because we have already extended the RouteAware abstract class. The second parameter is an instance of the type that was mentioned while initializing the RouteObserver. To check the type, go back to step 1.</p><p>As a rule of thumb, what is subscribed should also be unsubscribed. So, in the dispose method, we should unsubscribe the observer.</p><p>Yay! Now, your route is ready to listen to the navigator events. But, where will we get the callback for these events? That’s point number 5.</p><p>5. Overriding the <em>RouteObserver</em> methods,</p><p>Do Cmd+Click on RouteAware to jump to the definition, you will see it is an abstract class with 4 methods, you can simply override them as per your requirement, In case you don’t have your IDE open don’t worry we will go through them in the next section,</p><pre>class _BottomSheetWidgetState extends State&lt;BottomSheetWidget&gt; with RouteAware {<br><br>  @override<br>  void didPopNext() {<br>    print(&quot;Hey previous route is now popped!!&quot;);<br>  }<br>}</pre><blockquote>Side Note: You can use <em>didPopNext</em> to refresh your UI whenever user come back to this route from any other routes.</blockquote><p>We are done it&#39;s simple.</p><p>But it&#39;s always important to understand what are these classes and what functionality each of them provides, we will dive into that in the next section.</p><p>Scrolling my Insta feed …… Done!! Let’s get back.</p><p><strong><em>RouteObserver, —</em></strong></p><p>As per the definition, RouteObserver informs subscribers whenever a route of type R is pushed on top of their own route of type R or popped from it.</p><p>What should be passed as type R? In the above example, the ModalRoute has been passed, meaning that it listens to the state changes of all types of ModalRoute. Most of the default routes in Flutter use ModalRoute and, as seen in the definition, it is implemented by two classes., —</p><ul><li>PageRoute: A modal route that replaces the entire screen, examples,- MaterialPageRoute, CupertinoPageRoute</li><li>PopupRoute: A modal route that overlays a widget over the current route, for example,- Dialog, BottomSheet.</li></ul><p>So you can pass any of the routes as a type to the RouteObserver, depending on your use case.<br>For example, In <em>didPopNext </em>(Step 5), I might not want to listen to the bottom sheet or dialog pop events; I just need to listen to PageRoute pop events. So I will pass the type as PageRoute. <br>In the first example as we have passed ModalRoute, which is a parent of both of PageRoute and PopupRoute so it will listen to the transition of both of them.<br>In such cases, look at the inheritance hierarchy of the routes and choose the correct type you want to listen to.</p><p>If you look at the definition of the RouteObserver, it has methods like subscribe and unsubscribe and some overridden methods of NavigationObserver like didPush and didPop, these methods are overridden to provide more fine grain controls through RouteAware.</p><p>If you’re curious, jump to the definition and see what logic is written inside these methods.</p><p><strong><em>RouteAware</em></strong>,-</p><p>RouteObserver works closely with the RouteAware, RouteObserver emits the event to the routes which are “Route aware”, RouteAware classes are informed to the RouteObserver while subscribing to it (Step 4).</p><p>RouteAware is a layer of abstraction with a set of methods, as below:-</p><ul><li>didPop() — Called when the current route has been popped off.</li><li>didPopNext() — Called when the top route has been popped off, and the current route shows up.</li><li>didPush() — Called when the current route has been pushed.</li><li>didPushNext() — Called when a new route has been pushed, and the current route is no longer visible.</li></ul><p>— Definitions as per the official docs.</p><p>That’s too much theory, isn’t it? It is kind of important to understand and use the APIs to their fullest potential, in the next section, we will look at subscribing to transition events globally in your app.</p><p><em>Naah!! </em>Let’s focus and continue with no breaks.</p><p>Listening to global events is very simple you create a definition/class which extends RouteObserver, then initialize it, and pass it to the navigation observer, just 3 small steps and we are done,</p><ol><li>Extending the RouteObserver, -</li></ol><pre>class MyTransitionObserver extends RouteObserver&lt;ModalRoute&lt;dynamic&gt;&gt; {<br>  @override<br>  void didPush(Route&lt;dynamic&gt; route, Route&lt;dynamic&gt;? previousRoute) { }<br><br>  @override<br>  void didReplace({Route&lt;dynamic&gt;? newRoute, Route&lt;dynamic&gt;? oldRoute}) { }<br><br>  @override<br>  void didPop(Route&lt;dynamic&gt; route, Route&lt;dynamic&gt;? previousRoute) { }<br><br>  @override<br>  void didRemove(Route&lt;dynamic&gt; route, Route&lt;dynamic&gt;? previousRoute) { }<br><br>  @override<br>  void didStartUserGesture(Route&lt;dynamic&gt; route, Route&lt;dynamic&gt;? previousRoute) { }<br><br>  @override<br>  void didStopUserGesture() { }<br>}</pre><p>2. Initialising it,</p><pre>MyTransitionObserver analyticsObserver = MyTransitionObserver();</pre><p>3. Pass to the navigation observer, you already know this,</p><pre>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      navigatorObservers: [analyticsObserver],<br>    );<br>  }</pre><p>Now you can use this to track transition event and post it to the Event analytics platform, this is just one use case.<br>By the way in the case of Firebase you can do the global implementation in one line, just initialize the FirebaseAnalyticsObserver and you can report all the transition events to the Firebase.</p><p>They have an amazing implementation of Filter, with the help of which you can filter out the routes, which you do not want to report to the Firebase, curious? Jump to its definition to learn more.</p><p><strong>Summary</strong>:</p><ul><li>Implemented the Route Observer in just 5 simple steps? Can you recall?</li><li>Understood different classes associated with it, like RouteObserver and RouteAware .</li><li>Implemented an app-level transition tracking system.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=309ce2997c27" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/understanding-routeobserver-in-flutter-309ce2997c27">Understanding RouteObserver in Flutter</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Blocs: A Simple Introduction]]></title>
            <link>https://medium.com/better-programming/flutter-blocs-a-simple-introduction-8e948456d741?source=rss-452a6b29d9ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e948456d741</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sumit Ghosh]]></dc:creator>
            <pubDate>Fri, 18 Feb 2022 15:42:29 GMT</pubDate>
            <atom:updated>2022-02-20T07:00:33.422Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step by step guide to using Flutter Blocs in your project</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywReNjO4GN9Hu65eo1rRCA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kalaniparker?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kellen Riggin</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Are you finding it difficult to understand the working flutter_blocs library? Or you know it but might be getting confused while implementing it? Don’t worry we will go over step by step and understand everything in detail.</p><p>Flutter blocs provide a straightforward approach to handling different states in an app, once you understand it, it&#39;s easy to use and scale for any size of applications</p><h3><strong>Why do we even use Flutter Blocs?</strong></h3><blockquote><em>Bloc makes it easy to separate presentation from business logic, making your code </em>fast<em>, </em>easy to test<em>, and </em>reusable<em>. — Offical Bloc documentation</em></blockquote><p>Flutter Blocs simplifies doing state management in the app, it provides simple APIs to use, that abstracts lots of details and makes state management easier, it&#39;s one of the most popular state management libraries in Flutter and is actively maintained by <a href="https://github.com/felangel">Felix Angelov</a> and other open-source contributors.</p><p>As the name suggests Blocs handles all the business logic, be it interacting with the data layer to show something on UI or some complex computation.</p><p><strong>But, what is State Management? Can’t we ignore it, I mean we don’t use it on Android or iOS?</strong></p><p>No, we can’t, because Flutter is a declarative framework, it builds its UI to show the current state of the app, so whenever the state of the app changes we trigger a redraw of the UI, so basically for each state there is some UI, or as the official docs say, “UI is the function of the application state”.</p><p>for example, —</p><ul><li>Network not available State, you show a snack bar.</li><li>Fetch data State, you show a Loading indicator</li><li>Data is Fetched State, you show a Text widget with data, and so on.</li></ul><p>By the way, there are multiple state management solutions available in flutter but flutter_bloc is the most popular one.</p><p>We will add the <a href="https://pub.dev/packages/flutter_bloc">flutter_bloc</a> plugin as a dependency to our app, check for the latest version of the library, and add it to the pubspec.yml file of your project, under the dependencies section, the indentation should be proper, check the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6eS3LqW_vf94jENFwlih4A.png" /></figure><p>We will add a bloc extension to our IDE (available for both VSCode and Android Studio) as it helps in generating bloc files and reducing a lot of boilerplate.</p><p>Once you have added an extension, create a folder to store the bloc files and do Cmd+N on the folder, you will see an option of Bloc Class in the drop-down,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*pVTV2y7b2fK8CzvjdRYuLg.png" /></figure><p>Provide a name to your bloc, also you can choose to use Equitable. This generates three files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*uPceiNO15T9bEcARpgI_rQ.png" /></figure><p>We will go over them one by one, but before that let’s look at a very simple diagram to understand, each of these components and How they interact with the UI?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*8uBPdIa2KfYv3dqmjNnSdg.png" /><figcaption>Photo from <a href="https://bloclibrary.dev/#/">Bloc library Offical docs</a></figcaption></figure><p>So it is simple and straightforward, isn&#39;t it? Four steps are involved in this,</p><ul><li>UI triggers an event.</li><li>Bloc read’s the event runs some business logic.</li><li>After the computation is done, Bloc then emits a state.</li><li>UI listens to the state and updates itself accordingly.</li></ul><p>These are the three files, — Bloc, event, and state, go over the code snippets you can ignore “Will be used later”, comments I will be referring them in the next sections.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/615cf16140db9ad21224174f03c7777f/href">https://medium.com/media/615cf16140db9ad21224174f03c7777f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5763cc023aef33a853e8177f3e579450/href">https://medium.com/media/5763cc023aef33a853e8177f3e579450/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a89770caf18acb2b685ce7a57b4319a/href">https://medium.com/media/0a89770caf18acb2b685ce7a57b4319a/href</a></iframe><p>As the code snippets have a comment on each line, hope you got an idea of what these three files do, also visualize these components as shown in the bloc architecture diagram above.</p><p>So we have defined the Bloc Layer now let’s build a simple UI to see, how we can use this LoginBloc?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccb506bf12eec22ccafb744119cac58a/href">https://medium.com/media/ccb506bf12eec22ccafb744119cac58a/href</a></iframe><p>So in UI, we have added a text and button, on the tap of the button we will change the text. We will trigger an event on the button which will get a text from Bloc that we will display.</p><p>Wait! How will LoginScreen know about LoginBloc ?</p><p>Ah! Flutter Blocs already have a very elegant solution for this. As widgets are all around in Flutter, flutter blocs provide lots of useful widgets, as we progress with the example we will look into some of them in the next section.</p><p>We will go over the three questions to start using the Bloc, —</p><h4><strong>1. How to make Bloc available to the Widget tree (UI)?</strong></h4><p>The Widget which gives this functionality is the BlocProvider widget, BlocProvider makes the bloc available to the entire Widget tree, which is passed in the child parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93a8b38ea1baf1c21e881d47635b0821/href">https://medium.com/media/93a8b38ea1baf1c21e881d47635b0821/href</a></iframe><p>In the above code, we create a new instance of the LoginBloc, and as a child, we pass the instance of our LoginScreen , so Bloc Provider makes the LoginBloc available to the Widget tree of LoginScreen , Bloc Provider automatically handles the closing of the Bloc.</p><h4>2. <strong>How to trigger an Event from UI on some action?</strong></h4><p>Now that we have Bloc available on the Widget tree we can access it from anywhere, there are two ways to do that, —</p><p>a. Using context,</p><pre>context.read&lt;BlocA&gt;();</pre><p>b. Using Bloc Provider,</p><pre>BlocProvider.of&lt;BlocA&gt;(context)</pre><p><em>But what is the difference? When should we use which one?</em></p><p>There is actually not much difference both are almost the same, but the first one is defined as an extension on the BuildContext, so it’s easier to use. Proceed with whichever you like.</p><p>Let’s add a button tap event on the Bloc, —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ec19c8681ce6628324f62a5803daa0b/href">https://medium.com/media/9ec19c8681ce6628324f62a5803daa0b/href</a></iframe><blockquote>Note: — It’s important to pass the correct type of the Bloc, because it tries to lookup the tree to find the instance of that type, <a href="https://betterprogramming.pub/exploring-inherited-widget-in-flutter-10ab959017cb">you can read more on this here.</a></blockquote><p>Coming back to the Event, see how easy its to trigger an event from UI, we just call the addmethod on the Bloc, and pass an instance of an Event.</p><p>Now we need to go back to the Bloc and check if we have registered this event which is sent from the UI, on receiving this we will emit a State with a String to show on the UI, you can refer to the Bloc code attached above, just uncomment all the code with the comment “will be used later”. Great that’s it.</p><h4>3. <strong>But how will UI update itself when a new state is Emitted?</strong></h4><p>Yes, you guessed that right, there is a widget for this too. It’s called Bloc Consumer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eda2864c3b706eb3a245e8a88fd23000/href">https://medium.com/media/eda2864c3b706eb3a245e8a88fd23000/href</a></iframe><p>Let’s go over the BlocConsumer, though the above example contains the entire LoginScreen , but for now, you need to focus only on _buildScaffoldBody function.</p><p>If you notice the BlocConsumer , have four arguments let’s go over them one by one,</p><p>builder — It rebuilds the widget tree in response to the state changes, which means whenever you emit a new state it will rebuild the widgets so that you can use the value sent in the state that is emitted from the Bloc. So in this example, we have passed a text from the bloc in the UpdateTextStateand used it to so on the UI, this state is emitted whenever the “Tap me!!” button is tapped.</p><p>listener — So whenever a state is emitted the listener also gets invoked, but unlike builder, it doesn’t return any widget. It gets called once per state change, that’s why we generally use a listener that happens once whenever the state changes, like showing a snack bar, dialog, bottom sheet, or navigating to the next screen.</p><p>buildWhen — This is an optional parameter that provides previous and current states and returns a boolean, so if we return true it will call the builder, or else it won’t if you don’t use this parameter the builder will be called for each state change.</p><p>listenWhen — This is similar to buildWhen but used to control the Listener, if it returns true then the listener gets called.</p><p>So in our example, we are using Listener for ShowSnackBar state, which shows a snack bar with a text to display when the button is tapped. and we are using builder for LoginInitial , UpdateTextState , which updates the text on the screen when a button is tapped.</p><p>Another interesting point to note is that BlocConsumer takes in an optional parameter bloc, if you don’t provide it, it will try to lookup using BlocProvider and the current BuildContext . So if you missed injecting the Bloc (Question 1) it will throw an exception.</p><p>There will be cases where you either want to use builder or listener , for such cases there are different BlocBuilder and BlocListener widgets, feel free to explore them, also Flutter blocs provide some other helpful widgets but that’s for some other day.</p><h3>Summary</h3><ol><li>Build a UI (you have some business logic to run?).</li><li>Create a Bloc (Bloc, Event, and State classes).</li><li>Bind them together (Remember the three questions?).</li><li>Use BlocProvider to initialize the Bloc and make it available to the widget tree.</li><li>Use context to lookup the Bloc so, that you can add an event.</li><li>Perform your Business logic in the Bloc and emit the result.</li><li>Use BlocConsumer , BlocBuilder , BlocListener , to listen to the state changes and perform actions accordingly.</li></ol><h3>Useful Resources</h3><ul><li><a href="https://gist.github.com/Sumit-Ghosh/50f1a2c636eba6dcf7414c4dec734091">FlutterBloc official documentation</a></li><li><a href="https://www.youtube.com/watch?v=knMvKPKBzGE">Felix’s talk in Flutter Europe</a></li><li><a href="https://www.youtube.com/watch?v=THCkkQ-V1-8">Flutterly Bloc’s tutorial</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e948456d741" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/flutter-blocs-a-simple-introduction-8e948456d741">Flutter Blocs: A Simple Introduction</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Communicate Between Flutter and Native Android and iOS Code Using Platform Channel]]></title>
            <link>https://medium.com/better-programming/communicate-between-flutter-and-native-android-and-ios-code-using-platform-channel-7932f46b6aee?source=rss-452a6b29d9ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/7932f46b6aee</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Sumit Ghosh]]></dc:creator>
            <pubDate>Tue, 08 Feb 2022 16:26:21 GMT</pubDate>
            <atom:updated>2022-02-15T15:50:20.133Z</atom:updated>
            <content:encoded><![CDATA[<h3>Communicate Between Flutter and Native iOS Code Using Platform Channel</h3><h4>How to use Platform channel in Flutter</h4><figure><img alt="Person on laptop" src="https://cdn-images-1.medium.com/max/1024/0*_7VPqRdecjj0eKce.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@windows">Windows</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>While writing a flutter application you found that there is an action for which you need help from the native platform, you need to write a method to use native API, to establish a connection between flutter and native, and to allow the data to flow and to and fro we use Method channel</p><p><em>I have referred to “native” multiple times in this post. By “native,” I mean iOS and Android platforms.</em></p><p>Another use case is when you are adding a flutter module to a native app (Flutter addToApp), and in that case, you want to call some native method to pull in some information in your flutter module, you can use the method channel.</p><p>Lots of Flutter plugins internally use Platform Channels.</p><p>Here is an architectural overview:</p><figure><img alt="Flutter app client tied to the method channel which goes to the iOS host and Android host." src="https://cdn-images-1.medium.com/max/580/0*it3tRNmlLMecPMK5.png" /><figcaption>Photo by <a href="https://docs.flutter.dev/development/platform-integration/platform-channels">Flutter official docs</a></figcaption></figure><p>As we have already seen a few use cases, let’s dive into the details of the method channel with some code.</p><p>So first, we will initialize the Method channel as below:</p><pre>static const <em>platformChannel </em>= MethodChannel(&#39;test.flutter.methodchannel/iOS&#39;);</pre><p>So if you pasted this in your IDE, you might get some error. While investigating, you will find that it can’t identify the MethodChannel, so in order to use Platform, we need to import service package.</p><p>We used a <em>String</em> in method channel initializer, it is the method channel name, you can pass any String you like, but for standardization, it’s recommended to use the reverse <a href="https://en.wikipedia.org/wiki/Reverse_domain_name_notation">Reverse domain name notation</a>.</p><p>Apart from the required <em>name</em> parameter, the initializer takes in two more parameters:</p><ul><li>codec —<br>If no value is provided in this area, it uses StandardMethodCodec.</li></ul><blockquote>“The standard platform channels use a standard message codec that supports efficient binary serialization of simple JSON-like values, such as booleans, numbers, Strings, byte buffers, and Lists and Maps. The serialization and deserialization of these values too and from messages happen automatically when you send and receive values.” — Official docs</blockquote><ul><li>binaryMessenger(Optional)—<br>BinaryMessenger helps in sending the binary data to the native platforms,<br>If we don’t pass anything it uses defaultBinaryMessenger, in case you are curious about it, it is defined in the binding.dartfile.</li></ul><p>So in simple words binaryMessenger is used to pass the binary data to and from the native platform and codec is used for serialization and deserialization of these values.</p><p>Now we will write a method to get the iOS device model, as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe4b463dc9d0e7f829f7aec228db9504/href">https://medium.com/media/fe4b463dc9d0e7f829f7aec228db9504/href</a></iframe><p>Let’s walk through the code; it’s pretty straightforward.</p><ol><li>We are calling invokeMethod on the platform channel.<br>This method takes in the method name, and a list of arguments, in the above example we have omitted the list of arguments.<br>Note the method name because we have to use it in the native platform.</li><li>The platform might throw some exception so in order to be safe we will fall back to the catch block.<br><strong>Note</strong>: In the case of some platform-specific exception, it throws PlatformException.</li><li>We do setState which will rebuild the UI to show the device model.</li></ol><p>We are done on the Flutter side, will look into the iOS side implementation.</p><p>There is an iOS and Android folder in the flutter workspace, by default it’s at the same level as the lib folder, we will use these to write platform-specific code.</p><p>Open the iOS module in Xcode, and follow these steps:</p><ul><li>Locate your project in finder.</li><li>Go to the ios folder, if your project name is simple_platform_channel, then simple_platform_channel &gt; ios .</li><li>In the iOS folder open runner.xcworkspace</li></ul><p><strong>Note for non-iOS devs</strong>: Runner.xcodeproj is the project file, but as a Flutter project template by default uses Cocopods as a dependency manager it creates a workspace file that embeds dependencies.</p><p>Let’s write the native method, but were to write it?<br>Here is the path:</p><pre>Runner &gt; Runner &gt; AppDelegate</pre><p>You will see some code is already there. We will understand it before making any modifications.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/982b64df3e158c65bb88e00b19134d14/href">https://medium.com/media/982b64df3e158c65bb88e00b19134d14/href</a></iframe><p>There is an AppDelegate class that is annotated with @UIApplicationMain,<strong> </strong>so basically from this execution of the program begins, it&#39;s equivalent to void main() in Flutter.</p><p>Now if we see inside the class there is one method application with a parameter didFinishLaunchingWithOptions as the name indicates this method is executed as soon as the app launches. We will make changes to this method.</p><blockquote>Note: AppDelegate uses method overloading so there are lots of methods named as application but each one have a different parameter list.</blockquote><p>We will now use the PlatformChannel that we have defined in the Flutter.</p><p>Here is the code. Don’t worry if it looks scary; we will go over it step by step:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a60bb315110b2b3eb27dcd1901e5f1b/href">https://medium.com/media/0a60bb315110b2b3eb27dcd1901e5f1b/href</a></iframe><p>Let’s understand the above snippet:</p><ol><li>We are trying to get the FlutterViewController, in case you are wondering where did window come into the scene, it&#39;s basically defined in FlutterAppDelegate which is extended by the AppDelegate, and FlutterViewController is set as a rootViewControllerso, we are trying to access it.</li><li>Why are we creating a method channel again?<br>As we are trying to have an interaction between two frameworks the connections should be established on both sides.<br><strong>Note</strong>:<br>- In order to establish a connection, we need to have the same channel name as we have defined in the Flutter.<br>- binaryMessenger. We are using the default binary messenger provided by FlutterViewController. This is why we pulled out the FlutterViewController.</li><li>Here we are preparing the method handler. It will handle any method call invoked on the method channel.</li><li>We are attaching a method call back handler, and passing a closure (in case you are wondering what’s that, it’s just an anonymous function. If you’ve used List.forEach in flutter, then you know it already).<br>There are two parameters to the anonymous function:<br>- call ( FlutterMethodCall) — It provides the details of the method call, like method name and its arguments.<br>- result (FlutterResult) — This is the result you will return back to the flutter module, it’s denoted as the @escaping which means it’s an async call, so you can perform some time-taking operation and then call the result.</li><li>Just checking if the invoked method name is getDeviceModel. Here it doesn’t make much sense to check, but when there are multiple methods you need to check to distinguish between them.</li><li>Calling another method to get the device Model.</li><li>We have used the iOS device API to get the result.</li><li>Calling the result with the data, which helps in passing this back to the Flutter module.</li><li>If we invoke some method from the Flutter side which is not implemented in native we throw FlutterMethodNotImplemented.</li></ol><p>Simple isn’t it!</p><p>Now let’s look at some important questions around the platform channel.</p><p>How to pass some data from Flutter to iOS, while invoking a method?</p><p>Remember, we discussed the invokeMethod which takes in an array of dynamic args. Let’s see an example:</p><pre><em>platformChannel</em>.invokeMethod(&#39;getDeviceModel&#39;,<br>    {&quot;flutterAppVersion&quot;: &quot;0.0.1&quot;, &quot;developerName&quot;: &quot;XYZ&quot;});</pre><p>How to pass data back to the Flutter module?</p><p>We can pass any data in the result. For example:</p><pre>result( ------ )</pre><p>But in order to simplify things a bit, Flutter provide other alternatives to the invokeMethod:</p><pre>1. Future&lt;T?&gt; invokeMethod&lt;T&gt;(String method, [ dynamic arguments ])<br>2. Future&lt;Map&lt;K, V&gt;?&gt; invokeMapMethod&lt;K, V&gt;(String method, [ dynamic arguments ])<br>3. Future&lt;List&lt;T&gt;?&gt; invokeListMethod&lt;T&gt;(String method, [ dynamic arguments ])</pre><p>Though the parameter passed to this method are the same, the return types are different, so we can use invokeMapMethod if we want a map back in the result and so on.</p><h3>Summary</h3><p>In five simple steps, you can run platform-specific code in Flutter:</p><ol><li>Create a Method channel in Flutter.</li><li>Invoke a method on the channel and await the result.</li><li>Create a FlutterMethodChannel in iOS, in the application method with didFinishLaunchingWithOptions.</li><li>Set the callback handler on the channel.</li><li>Use the native APIs to perform some action and return the result.</li></ol><h3>Resources</h3><p>Some useful resources on the Platform channel:</p><ul><li><a href="https://docs.flutter.dev/development/platform-integration/platform-channels?tab=type-mappings-swift-tab#codec">Data supported by different platforms</a></li><li><a href="https://docs.flutter.dev/development/platform-integration/platform-channels">Platform Channels: Offical docs</a></li><li><a href="https://docs.flutter.dev/development/platform-integration/platform-channels?tab=type-mappings-swift-tab#step-3-add-an-android-platform-specific-implementation">Android Platform implementation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7932f46b6aee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/communicate-between-flutter-and-native-android-and-ios-code-using-platform-channel-7932f46b6aee">Communicate Between Flutter and Native Android and iOS Code Using Platform Channel</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Inherited Widget in Flutter]]></title>
            <link>https://medium.com/better-programming/exploring-inherited-widget-in-flutter-10ab959017cb?source=rss-452a6b29d9ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/10ab959017cb</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Sumit Ghosh]]></dc:creator>
            <pubDate>Mon, 24 Jan 2022 11:55:05 GMT</pubDate>
            <atom:updated>2022-01-24T11:55:05.227Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understand how to use inherited widgets with an example</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pUi3vkj06Vqp_sXeiI-UbQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jstrippa">James Harrison</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Consider a use case where you want to update some element in the widget tree when internet connectivity is not available. One possible way to achieve it is by using an Inherited widget, it solves such use-cases where you want to access the data from anywhere above the tree.</p><p>You might have already used the inherited widget unknowingly in Flutter. As Flutter framework uses it internally in order to solve multiple uses case such as Theming, Device sizing, routing, and so on.</p><h3><strong>But what is Inherited Widget?</strong></h3><p>You have multiple widgets nested in a widget tree, and you are trying to access the data which is somewhere up the tree.</p><p>We could propagate the data through the constructor, but isn’t that cumbersome, so the inherited widget comes into the picture.</p><p>If your widget tree is a child of an inherited widget, then you can access the data anywhere in the widget tree.</p><p>We will go over step by step, and see how to use the inherited widgets?</p><p>So in order to use the Inherited widget, you have to extend it in your class. For example:</p><pre>class InheritedNetworkHandler extends InheritedWidget { </pre><pre>}</pre><p>But as soon as you extend InheritedWidget the compiler complains, —“ Missing concrete implementation of InheritedWidget.updateShouldNotify<em>”. </em>If you jump to the definition of Inherited widget (cmd + click), you would see it is defined as an Abstract<strong> </strong>class, with two methods:-</p><ul><li>createElement, which is an overridden method.</li><li>updateShouldNotify, which is an unimplemented method.</li></ul><p>We will look into this method, let fix the error,-</p><pre>class InheritedNetworkHandler extends InheritedWidget {</pre><pre>  @override<br>  bool updateShouldNotify(InheritedWidget oldWidget) {<br>    return true;<br>  }<br>}</pre><p><strong>Return type</strong>:<br>The return value determines whether Flutter should re-draw the widgets when the data in the Inherited Widget changes.</p><blockquote>Note:- In the case of redraw it will only redraw that widget that is using the Inherited widget.</blockquote><p><strong>Parameter</strong>:<br>But what does the parameter name OldWidget means?<br>OldWidget is an inherited widget, with the old data, before it is rebuilt with a new one.</p><p>What is this data, that I referred to in the past few lines?</p><p>Before we get there you might still see the compiler is complaining about some error. We will oblige to complier suggestion, and don’t forget to pass the child parameter to the superclass, as it’s a required parameter. The child is the tree that will consume the inherited widget’s data.</p><p>The updated code looks as below:</p><pre>class InheritedNetworkHandler extends InheritedWidget {</pre><pre>  const InheritedNetworkHandler({required Widget child}) :      super(child: child);</pre><pre>  @override<br>  bool updateShouldNotify(covariant InheritedWidget oldWidget) {          return true;<br>  }<br>}</pre><p>So coming back to data, it is a field that is defined in the inherited widget. This field can be accessed throughout the child widget tree. We will add a field to our inherited widget:</p><pre>class InheritedNetworkHandler extends InheritedWidget {</pre><pre>  // Data hold by inherited widget<br>  final bool isNetworkAvailable;</pre><pre>  const InheritedNetworkHandler({required this.isNetworkAvailable, required Widget child}): super(child: child);</pre><pre>  @override<br>  bool updateShouldNotify(covariant InheritedWidget oldWidget) { return true;<br>  }<br>}</pre><p>So here we defined isNetworkAvailable property in the InheritedNetworkHandler<em>.</em></p><blockquote>Note:- <em>isNetworkAvailable</em> is marked as final because the Inherited widget is immutable, which means this data won’t change in the app life cycle.<br>The only way to change it, is by rebuilding the inherited widget.</blockquote><p>Now we can access the value of the inherited widget in any of the child widgets,</p><pre>class ChildWidget extends StatelessWidget {<br>  const ChildWidget({Key? key}) : super(key: key);</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>  <br>    // Something new?<br>    final bool? isNetworkAvailable =   context.dependOnInheritedWidgetOfExactType&lt;InheritedNetworkHandler&gt;()?.isNetworkAvailable;</pre><pre>    return Container();<br>  }<br>}</pre><p>We are using a method dependOnInheritedWidgetOfExactType. As the name suggests it tries to find the concrete implementation of the given type T, up the widget tree.</p><p>But isn’t that too long to be used across widgets?</p><p>Yes, it is, we will simplify it. We will add it as a helper method to the InheritedNetworkHandler:</p><pre>class InheritedNetworkHandler extends InheritedWidget {<br>  ...</pre><pre>  static InheritedNetworkHandler? <em>of</em>(BuildContext context) =&gt; context.dependOnInheritedWidgetOfExactType&lt;InheritedNetworkHandler&gt;();<br>}</pre><p>We defined a static helper method of which takes BuildContext as a parameter and returns an InheritedNetworkHandler. Let’s use it in the child widget.</p><pre>class ChildWidget extends StatelessWidget {<br>  const ChildWidget({Key? key}) : super(key: key);</pre><pre>@override<br>  Widget build(BuildContext context) {<br>  <br>    // Updated version<br>    final bool? isNetworkAvailable = InheritedNetworkHandler.<em>of</em>(context)?.isNetworkAvailable;;</pre><pre>   return Container();<br>  }<br>}</pre><p>Have you come across of method before?</p><ul><li>MediaQuery.of(context)</li><li>Navigator.of(context)</li></ul><p>See I told you that you have already used an Inherited widget, so if you jump to the definition of the of<em> </em>method, it also uses dependOnInheritedWidgetOfExactType<em>. </em>Now every time you use .of(context)<em> </em>you know what it does.</p><p>We will connect the pieces together, and see the entire code.</p><p>For the sake of this implementation, I have used the <a href="https://pub.dev/packages/connectivity_plus">connectivity_plus</a> plugin.<br>Also will wrap our InheritedWidget around a Stateful widget, so that any changes in the state of this widget rebuild the InheritedWidget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a2921bd35882821d40d026e966bc5e0/href">https://medium.com/media/9a2921bd35882821d40d026e966bc5e0/href</a></iframe><p>This is the implementation of the Inherited Widget, now we’ll see the usage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ff4f642305e0edef44517f765830c12/href">https://medium.com/media/0ff4f642305e0edef44517f765830c12/href</a></iframe><blockquote>You can access the Inherited Widget within the context in which it is defined.</blockquote><p>In the above example, context can be used only by the ChildWidget subtree.<br>In case you Navigate to a new route, you won’t be able to access the Inherited widget as the context changes.</p><p>If you want to access the Inherited widget in the entire app wrap the MaterialWidget with your inherited widget (option 2 in the above snippet).</p><p>In case you are wondering if the entire tree needs to be rebuilt when I update the data in the inherited widget, the answer is no.</p><p>Flutter performs certain optimization and it rebuilds only the widget that is using data from the Inherited widget.</p><h3>Resources</h3><p>Some useful resources on Inherited widget from the Flutter team,</p><ul><li><a href="https://www.youtube.com/watch?v=Zbm3hjPjQMk">Inherited Widget Explained</a></li><li><a href="https://www.youtube.com/watch?v=1t-8rBCGBYw">Inherited Widget (Widget of the week)</a></li><li><a href="https://www.youtube.com/watch?v=LFcGPS6cGrY">Manage application state using Inherited Widget</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10ab959017cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/exploring-inherited-widget-in-flutter-10ab959017cb">Exploring Inherited Widget in Flutter</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>