<?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 Edson Bueno on Medium]]></title>
        <description><![CDATA[Stories by Edson Bueno on Medium]]></description>
        <link>https://medium.com/@ejr.bueno?source=rss-6de0af483df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*0fYo2kCxkSysafCPf8Btgg.jpeg</url>
            <title>Stories by Edson Bueno on Medium</title>
            <link>https://medium.com/@ejr.bueno?source=rss-6de0af483df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 03:13:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ejr.bueno/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[Bringing onResume/viewDidAppear onPause/viewDidDisappear to Flutter]]></title>
            <link>https://medium.com/flutter-community/bringing-onresume-viewdidappear-onpause-viewdiddisappear-to-flutter-dbd906845b90?source=rss-6de0af483df------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbd906845b90</guid>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Edson Bueno]]></dc:creator>
            <pubDate>Wed, 26 Feb 2020 07:00:00 GMT</pubDate>
            <atom:updated>2020-12-25T14:05:15.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6sWKyu_ZvRDNZiBRA8dpQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@purzlbaum">Claudio Schwarz</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Intro</h3><p>If I ask you to develop a page that fetches its information as soon as we open it, you’d probably be done in a couple of minutes. You have a variety of hooks to choose for doing the job. Maybe <a href="https://api.flutter.dev/flutter/widgets/State/initState.html">initState</a>, <a href="https://api.flutter.dev/flutter/widgets/State/didChangeDependencies.html">didChangeDependencies</a> with a control flag, your BLoC&#39;s constructor or anything similar, and they would all work just fine.</p><p>But now, what if I ask you to re-fetch the same info whenever the page <em>appears</em> on screen instead of only when it is <em>first opened</em>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*-Dr8LVaJUcs433lz.gif" /><figcaption>Refreshing the info whenever the page appears on screen.</figcaption></figure><h3>Every Time the Page Appears on Screen?</h3><p>In other words: every time the page has the focus.</p><p>That encompasses three scenarios:</p><ol><li>When we first open it;</li><li>When we come back to it after opening another page;</li><li>When we put the app in the background while the page was on screen, and then bring the app back to the foreground;</li></ol><p>Native mobile developers acknowledge this as using the <a href="https://developer.android.com/reference/android/app/Fragment#onResume()">onResume</a> or <a href="https://developer.apple.com/documentation/uikit/uiviewcontroller/1621423-viewdidappear">viewDidAppear</a> callback, but in Flutter, there wasn&#39;t a dead-simple way to accomplish the same.</p><p>Your first impulse will tell you to use the <a href="https://api.flutter.dev/flutter/widgets/State/build.html">build</a> method, but that’s a terrible idea because it runs anytime your widget needs to rebuild, and that happens quite a lot.</p><p>Then, after spending some time at Google or StackOverflow, <a href="https://api.flutter.dev/flutter/widgets/RouteObserver-class.html">RouteObserver</a> along with <a href="https://api.flutter.dev/flutter/widgets/RouteAware-class.html">RouteAware</a> widgets will pop at you. It&#39;s a way to register your widget to be notified whenever we push and pop back to its <a href="https://api.flutter.dev/flutter/widgets/Route-class.html">Route</a>. Problems? It won&#39;t effortlessly work if you use nested <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a>s. Think about it: if you use, for example, a <a href="https://edsonbueno.com/2020/01/23/bottom-navigation-in-flutter-mastery-guide/">bottom navigation structure</a>, there are two ways in which your page can appear on screen:</p><ol><li>If we push or pop back to its <a href="https://api.flutter.dev/flutter/widgets/Route-class.html">Route</a>;</li><li>If we push or pop back to its “parent widget’s <a href="https://api.flutter.dev/flutter/widgets/Route-class.html">Route</a>“ (the page holding the bottom navigation menu);</li></ol><p>To cover the second case, we would have to do all the <a href="https://api.flutter.dev/flutter/widgets/RouteAware-class.html">RouteAware</a> set up on the parent widget as well and find a way to propagate the event down the tree. If it sounded like a lot of work, that&#39;s because it is! Also, it wouldn&#39;t cover the scenario in which we put the app in the background and then bring it to the foreground again, as the pushed route&#39;s remained the same.</p><p>Thankfully, some guys at Google (apparently not from the core Flutter team) provided us a package that gets us closer to what we want.</p><h3>The VisibilityDetector Package</h3><blockquote><em>A VisibilityDetector widget wraps an existing Flutter widget and fires a callback when the widget’s visibility changes.</em></blockquote><p>It looks that now we have everything figured out, right?!</p><p>Not yet! 😩</p><p>The <a href="https://github.com/google/flutter.widgets/blob/master/packages/visibility_detector/lib/visibility_detector.dart">VisibilityDetector</a> won&#39;t detect the case in which we bring the app back to the foreground while the widget was visible. Fortunately, Flutter <em>does</em> have an easy way for covering that: <a href="https://api.flutter.dev/flutter/widgets/WidgetsBindingObserver-class.html">WidgetsBindingObserver</a>. We just need to combine it with the <a href="https://github.com/google/flutter.widgets/blob/master/packages/visibility_detector/lib/visibility_detector.dart">VisibilityDetector</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*A6KPQh4x6XVYQ1qo.gif" /></figure><h3>The FocusDetector Package Was Born</h3><p><a href="https://pub.dev/packages/focus_detector">https://pub.dev/packages/focus_detector</a></p><h3>Usage</h3><p>If you’ve followed my previous posts, you know that I have this <a href="https://github.com/EdsonBueno/breaking_bapp"><em>Breaking Bapp</em></a> project I like using for showcasing. It uses a simple master-detail pattern for displaying <a href="https://en.wikipedia.org/wiki/Breaking_Bad">Breaking Bad</a> ‘s info.</p><p>From a product perspective, it isn’t the best use case for the <a href="https://pub.dev/packages/focus_detector">FocusDetector</a>. Re-fetching information every time the page gains the focus isn&#39;t useful at all for an app like this. It only consumes unnecessary bandwidth and makes the app slower.</p><p>On the other hand, as far as the code goes, its simplicity is ideal for you to see the <a href="https://pub.dev/packages/focus_detector">FocusDetector</a> in action.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3177dc244128b691538c6cdb92cf096/href">https://medium.com/media/a3177dc244128b691538c6cdb92cf096/href</a></iframe><p>That’s all! It couldn’t be simpler!</p><p>Previously, the above code was calling the _fetchCharacterSummaryList method on the <a href="https://api.flutter.dev/flutter/widgets/State/initState.html">initState</a> callback. You can see the initial and final versions by checking out the focus-detector/set-state-initial and focus-detector/set-state-bloc-detector branches, respectively, of the <a href="https://github.com/EdsonBueno/breaking_bapp">GitHub Repository</a>.</p><h3>Bonus</h3><p>For an example using BLoCs, compare the focus-detector/bloc-initial and focus-detector/bloc-focus_detector branches.</p><h3>Like what you read?</h3><p>If you want more in-depth articles like this, leave your e-mail <a href="https://edsonbueno.us4.list-manage.com/subscribe?u=344054ac1436a4189f9b824fd&amp;id=08a7d84462">here</a> and stay up to date with what I write.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbd906845b90" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-community/bringing-onresume-viewdidappear-onpause-viewdiddisappear-to-flutter-dbd906845b90">Bringing onResume/viewDidAppear onPause/viewDidDisappear to Flutter</a> was originally published in <a href="https://medium.com/flutter-community">Flutter Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bottom Navigate Like the Pros in Flutter]]></title>
            <link>https://medium.com/swlh/bottom-navigate-like-the-pros-in-flutter-8a48bdd5fed4?source=rss-6de0af483df------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a48bdd5fed4</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <dc:creator><![CDATA[Edson Bueno]]></dc:creator>
            <pubDate>Thu, 23 Jan 2020 09:56:20 GMT</pubDate>
            <atom:updated>2020-12-09T09:25:45.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fd3nflFf__GS2HH3TB8oNg.png" /></figure><h3>Intro</h3><p><a href="https://material.io/components/bottom-navigation/">Bottom navigation</a> has skyrocketed in popularity in the last few years. It came out as an alternative to the <em>not so popular anymore</em> hamburger menus or <a href="https://material.io/components/navigation-drawer/">navigation drawers</a>. Implementing it using Flutter is easy if we want to show the bottom bar <em>only</em> when displaying one of the initial pages, i.e., those directly exposed on the menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*mv9RjLvXJjMb7hOB.gif" /><figcaption>Simple bottom navigation where the bar is no longer visible once we open a new page.</figcaption></figure><p>But that’s not how the cool kids are doing it. Apps like Youtube and Instagram, allows navigation to happen <em>inside</em> tabs, keeping the bottom menu visible for you to shift between them at any time. It also manages separate “navigation stacks” for each, so that they won’t interfere with one another, and allowing you to continue from where you left when you switch back.</p><p>In this article, we’ll cover how you can achieve the same. By the end of it, you’ll have a complete understanding of how this works by building a solution that goes incrementally from what you saw in the gif above, to a top-notch solution that even adapts to the device’s platform. I divided that goal into three manageable tasks that we must solve to conquer it. I hope you enjoy it.</p><p><strong>README.md 😉</strong></p><ul><li>I’ll use the terms <em>screen</em> and <em>page</em> interchangeably.</li><li>I’ll use the word <em>flow</em> when referring to a collection of related pages.</li><li><em>Menu</em> and <em>bar</em> will also be used interchangeably.</li><li><a href="https://github.com/EdsonBueno/adaptive_bottom_nav_sample">The code sample is available on GitHub</a>, and I’ll reference the branch name whenever useful. You can find the code for the first image at simple-nav-home-only.</li></ul><h3>First Task</h3><p><strong>Showing the bottom menu in other pages besides the initials.</strong></p><p>People often refer to this pattern as <em>Instagram-like navigation</em>. It goes like this: instead of one <em>page</em>, we’ll have a <em>stack of pages</em> per tab, enabling us to keep the bar visible while the user navigates inside it.</p><p>If we want to present another flow of our app, one that isn’t on the bottom menu, like an authentication flow or merely a fullscreen dialog, we still can/should, but then the bar won’t remain visible.</p><p>In summary, for each new page we want to show we have two possibilities:</p><p>1.Push it inside our current <em>inner</em> stack, i.e., navigating deeper into our flow — <strong>horizontal navigation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*tjI5_cssiBua18Nv.gif" /><figcaption>Navigating inside our currently opened tab’s flow. The menu remains visible all the time.</figcaption></figure><p>2.Push it to our <em>outer/top-level</em> stack, i.e., presenting it as another flow — <strong>vertical navigation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*VPkNxho2j3H4RHp5.gif" /><figcaption>Presenting to the user another flow, e.g., authentication. The bottom navigation menu isn’t visible anymore.</figcaption></figure><p>This concept is very familiar to those with an iOS background, as it is standardized over there.</p><p><strong>Solution: Having one </strong><a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html"><strong>Navigator</strong></a><strong> widget per tab.</strong></p><p>By default, inside our <a href="https://api.flutter.dev/flutter/material/MaterialApp-class.html">MaterialApp</a>/<a href="https://api.flutter.dev/flutter/cupertino/CupertinoApp-class.html">CupertinoApp</a>, we&#39;re already given a stack to push and pop our pages widgets, but one isn&#39;t enough anymore.</p><p>Since in Flutter <em>“everything is a widget”</em>, we need one that is capable of managing its separate stack of pages, so that each of our flows can have one of these. For that purpose, we have the <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a> widget:</p><blockquote><em>A widget that manages a set of child widgets with a stack discipline.</em></blockquote><p>Sounds great, right? If we wrap each flow with one of these, what’s left for us when navigating, is choosing if we want to push the new screen in the current/inner <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a>, for navigating horizontally, or in the <a href="https://api.flutter.dev/flutter/material/MaterialApp-class.html">MaterialApp</a>/<a href="https://api.flutter.dev/flutter/cupertino/CupertinoApp-class.html">CupertinoApp</a>&#39;s one, for vertical navigation.</p><h4>“Talk is cheap. Show me the code.”</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7e89669f7d572d57b85f899b6a3062f/href">https://medium.com/media/e7e89669f7d572d57b85f899b6a3062f/href</a></iframe><p>This class is our entry point, the widget I’m giving to the <a href="https://api.flutter.dev/flutter/material/MaterialApp-class.html">MaterialApp</a>&#39;s <a href="https://api.flutter.dev/flutter/material/MaterialApp/home.html">home</a> property. It&#39;s called Screen, not Page, to avoid confusion. Conceptually, this one <em>displays</em> pages inside it rather than <em>being</em> one.</p><p>The code for the IndexedPage widget is straightforward and adds nothing to our guide. It&#39;s just a column with two buttons, but you can see it <a href="https://github.com/EdsonBueno/adaptive_bottom_nav_sample/blob/simple-nav-loosing-state/lib/indexed_page.dart">here</a> or by checking out the simple-nav-loosing-state branch. The only part worth mentioning is that when we&#39;re navigating vertically, we should pass true to the rootNavigator parameter of the <a href="https://api.flutter.dev/flutter/widgets/Navigator/of.html">Navigator.of</a> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8fc7078e1810c7a25f86d81e48e815a/href">https://medium.com/media/a8fc7078e1810c7a25f86d81e48e815a/href</a></iframe><h3>Second Task</h3><p><strong>Maintaining state across tab switches.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*3drmdQG0uM--S-OZ.gif" /><figcaption>Notice that when we come back to the previous tab, it is displaying Page 1 again rather than Page 3.</figcaption></figure><p>Our code has a problem now. When we’re navigating through a flow, switch to another, and then come back to the previous, it will be showing its first page again. If this was a real-world app, for example, the user might be filling a form, and wouldn’t be happy to lose it.</p><p><strong>Solution: Keeping both tab’s </strong><a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html"><strong>Navigator</strong></a><strong>s in the widget tree.</strong></p><p>Instead of recreating our flows each time the selected tab changes, this time we want to hold them. We can accomplish that by keeping all in the widget tree, while only displaying one. Here comes the <a href="https://api.flutter.dev/flutter/widgets/IndexedStack-class.html">IndexedStack</a> widget:</p><blockquote><em>A Stack that shows a single child from a list of children. The displayed child is the one with the given index.</em></blockquote><p>Kudos to <a href="https://medium.com/@hansmuller_64350">Hans Muller</a> on doing the <a href="https://medium.com/flutter/getting-to-the-bottom-of-navigation-in-flutter-b3e440b9386">excellent job</a> of walking us through that.</p><p>Here’s the diff from our previous version of the HomeScreen:</p><pre>child: Scaffold(<br>-        body: Navigator(<br>-          // The key in necessary for two reasons:<br>-          // 1 - For the framework to understand that we&#39;re replacing the<br>-          // navigator even though its type and location in the tree is<br>-          // the same. For this isolate purpose a simple ValueKey would fit.<br>-          // 2 - Being able to access the Navigator&#39;s state inside the onWillPop<br>-          // callback and for emptying its stack when a tab is re-selected.<br>-          // That is why a GlobalKey is needed instead of a simple ValueKey.<br>-          key: currentFlow.navigatorKey,<br>-          // Since this isn&#39;t the purpose of this sample, we&#39;re not using named<br>-          // routes. Because of that, the onGenerateRoute callback will be<br>-          // called only for the initial route.<br>-          onGenerateRoute: (settings) =&gt; MaterialPageRoute(<br>-            settings: settings,<br>-            builder: (context) =&gt; IndexedPage(<br>-              index: 1,<br>-              containingFlowTitle: currentFlow.title,<br>-              backgroundColor: currentFlow.mainColor,<br>-            ),<br>-          ),<br>+        body: IndexedStack(<br>+          index: _currentBarIndex,<br>+          children: appFlows<br>+              .map(<br>+                _buildIndexedPageFlow,<br>+              )<br>+              .toList(),<br>         ),<br>         bottomNavigationBar: BottomNavigationBar(<br>           currentIndex: _currentBarIndex,<br>           items: appFlows<br>               .map(<br>                 (flow) =&gt; BottomNavigationBarItem(<br>                   label: flow.title,<br>                   icon: Icon(flow.iconData),<br>                 ),<br>               )<br>               .toList(),<br>           onTap: (newIndex) =&gt; setState(<br>             () {<br>               if (_currentBarIndex != newIndex) {<br>                 _currentBarIndex = newIndex;<br>               } else {<br>                 // If the user is re-selecting the tab, the common<br>                 // behavior is to empty the stack.<br>                 currentFlow.navigatorKey.currentState<br>                     .popUntil((route) =&gt; route.isFirst);<br>               }<br>             },<br>           ),<br>         ),<br>       ),<br>     );<br>   }<br>+<br>+  // The best practice here would be to extract this to another Widget,<br>+  // however, moving it to a separate class would only harm the<br>+  // readability of our guide.<br>+  Widget _buildIndexedPageFlow(AppFlow appFlow) =&gt; Navigator(<br>+        // The key enables us to access the Navigator&#39;s state inside the<br>+        // onWillPop callback and for emptying its stack when a tab is<br>+        // re-selected. That is why a GlobalKey is needed instead of<br>+        // a simpler ValueKey.<br>+        key: appFlow.navigatorKey,<br>+        // Since this isn&#39;t the purpose of this sample, we&#39;re not using named<br>+        // routes. Because of that, the onGenerateRoute callback will be<br>+        // called only for the initial route.<br>+        onGenerateRoute: (settings) =&gt; MaterialPageRoute(<br>+          settings: settings,<br>+          builder: (context) =&gt; IndexedPage(<br>+            index: 1,<br>+            containingFlowTitle: appFlow.title,<br>+            backgroundColor: appFlow.mainColor,<br>+          ),<br>+        ),<br>+      );<br> }</pre><p>That’s enough for preventing our stack of pages from being emptied each time we switch tabs. You can find this version at the stateful_nav_material branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*g6VRQwXzAcJUczZF.gif" /><figcaption>Retaining tab’s state across tab switches.</figcaption></figure><h3>Third Task</h3><p><strong>Make it look like iOS’ and Android’s native bottom navigation components.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*Zcx_ncGNM9A9lpODUEPKxg.gif" /><figcaption>Material’s bottom navigation bar.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*BMfBqZypkpytVfPqXDQPpQ.gif" /><figcaption>Cupertino&#39;s bottom navigation bar.</figcaption></figure><p>I took both screenshots from the final version of our app. Notice that on the Cupertino’s, there is no splash effect on selection, the icons are bigger and the titles smaller. Of course, that’s only a concern if you want your app to look exactly like the natives.</p><p><strong>Solution: Building a platform-aware widget.</strong></p><p>We use the term <em>platform-aware</em>, or simply <em>adaptive</em>, when referring to widgets that render differently depending on the device’s platform.</p><p>The good news is that the equivalent <a href="https://api.flutter.dev/flutter/cupertino/cupertino-library.html">Cupertino</a>&#39;s widgets for what we’ve done so far, already handles by default tasks one and two for us.</p><p>If we were to close our eyes to the third task, we would have two paths to follow:</p><ol><li>Use our current implementation on both platforms, the downside being that it looks like Android’s native component.</li><li>Use the <a href="https://api.flutter.dev/flutter/cupertino/CupertinoTabScaffold-class.html">CupertinoTabScaffold</a> widget on both platforms, the downside being that now it looks like the iOS&#39; native component.</li></ol><p>But, as the great developers that we all are, we won’t ignore the third task. I promised you a top-notch solution, and that’s what you’ll get. 😎</p><h4>Step-by-step on becoming adaptive</h4><p>1.In our IndexedPage, we’re pushing routes using the <a href="https://api.flutter.dev/flutter/material/MaterialPageRoute-class.html">MaterialPageRoute</a> class. Let’s make it more professional by using a <a href="https://api.flutter.dev/flutter/cupertino/CupertinoPageRoute-class.html">CupertinoPageRoute</a> when we’re on iOS:</p><pre>void _pushPage(BuildContext context, bool isHorizontalNavigation) {<br>    // If it&#39;s not horizontal navigation,<br>    // we should use the rootNavigator.<br>    Navigator.of(context, rootNavigator: !isHorizontalNavigation).push(<br>-      MaterialPageRoute(<br>+      _buildAdaptivePageRoute(<br>        builder: (context) =&gt; IndexedPage(<br>          // If it&#39;s a new flow, the displayed index should be 1 again.<br>          index: isHorizontalNavigation ? index + 1 : 1,<br>          // If it&#39;s a new flow, we&#39;ll randomize its color.<br>          backgroundColor: isHorizontalNavigation<br>              ? backgroundColor<br>              : Colors.primaries[Random().nextInt(Colors.primaries.length)],<br>          // If it&#39;s starting a new flow let&#39;s just call it &#39;New.&#39;<br>          containingFlowTitle:<br>              isHorizontalNavigation ? containingFlowTitle : &#39;New&#39;,<br>        ),<br>        fullscreenDialog: !isHorizontalNavigation,<br>      ),<br>    );<br>  }<br>+  <br>+  PageRoute&lt;T&gt; _buildAdaptivePageRoute&lt;T&gt;(<br>+          {<a href="http://twitter.com/required">@required</a> WidgetBuilder builder, bool fullscreenDialog = false}) =&gt;<br>+      Platform.isAndroid<br>+          ? MaterialPageRoute(<br>+              builder: builder, <br>+              fullscreenDialog: fullscreenDialog,<br>+            )<br>+          : CupertinoPageRoute(<br>+              builder: builder, <br>+              fullscreenDialog: fullscreenDialog,<br>+            );</pre><p>That will handle the different transition animations between platforms for us.</p><p>2.Fortunately, both the Material’s solution we built and the Cupertino’s widgets composition for achieving the same (we’ll get there) uses the same <a href="https://api.flutter.dev/flutter/widgets/BottomNavigationBarItem-class.html">BottomNavigationBarItem</a> class for representing the tabs, a <a href="https://api.flutter.dev/flutter/widgets/GlobalKey-class.html">GlobalKey</a> for its inner navigators, and both needs a builder for the initial page of each flow. So, I’ve created a wrapper class in a separate file for these dependencies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f457b97faabd700b33919e76176808cf/href">https://medium.com/media/f457b97faabd700b33919e76176808cf/href</a></iframe><p>3.Let’s move our Material’s specific code out of the HomeScreen and into another widget called MaterialBottomNavigationScaffold. Notice that it knows nothing about the domain of our app (music and videos).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dbb1b7b9296764c9021755bbe8682a4/href">https://medium.com/media/5dbb1b7b9296764c9021755bbe8682a4/href</a></iframe><p>4.Create the <a href="https://api.flutter.dev/flutter/cupertino/cupertino-library.html">Cupertino</a>’s analogous to our recently created MaterialBottomNavigationScaffold. These are all classes brought to us by the <a href="https://api.flutter.dev/flutter/cupertino/cupertino-library.html">Cupertino</a> library, and since it already handles by default tasks one and two for us, the code is self-explanatory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92ae032f2a61faf969ff4f606ef361ab/href">https://medium.com/media/92ae032f2a61faf969ff4f606ef361ab/href</a></iframe><p>5.Create a Scaffold class that chooses between our Material’s and Cupertino’s and also implements the common behavior to both.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfbfa4202fec9b727fe1542df3f491d4/href">https://medium.com/media/dfbfa4202fec9b727fe1542df3f491d4/href</a></iframe><p>6.Change the HomeScreen to use our newly born AdaptiveBottomNavigationScaffold and keep only our domain specifics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/312be2da4d95562ba51b5980201ac102/href">https://medium.com/media/312be2da4d95562ba51b5980201ac102/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*rXSYIGVcjQBn8C7x8dIRnw.gif" /><figcaption>Material’s final version.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*voQNQ-xBVaLsL0O_FnUGmg.gif" /><figcaption>Cupertino’s final version.</figcaption></figure><p>And you’re done! This complete version is available at the adaptive-stateful-nav branch.</p><p>Notice that although we made our bottom navigation bar and route transition animations look different on each platform, our <a href="https://github.com/EdsonBueno/adaptive_bottom_nav_sample/blob/adaptive_stateful_nav/lib/indexed_page.dart">IndexedPage</a> doesn&#39;t. That&#39;s why we still have this <a href="https://api.flutter.dev/flutter/material/material-library.html">Material</a> feel on our buttons and app bars, but let&#39;s leave this for another article.</p><h3>Recap</h3><p>We started with the simplest possible solution, where the bottom menu was visible only when showing the initial pages, then solved that by having multiple <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a>s. Next, we identified that we were losing state, so we used an <a href="https://api.flutter.dev/flutter/widgets/IndexedStack-class.html">IndexedStack</a> for helping us with that. Last but not least, we gave it different looks on each platform by building Material&#39;s and Cupertino&#39;s versions and choosing between them based on the platform we&#39;re currently running. It may seem like a lot, but now you have a full-fledged solution to use in every production project you need to.</p><h3>Bonus</h3><p>Check out the master branch to see how I added cross-fade transitions and lazy widget building to <a href="https://github.com/EdsonBueno/adaptive_bottom_nav_sample/blob/master/lib/custom/material_bottom_navigation_scaffold.dart">MaterialBottomNavigationScaffold</a> as taught by <a href="https://medium.com/flutter/getting-to-the-bottom-of-navigation-in-flutter-b3e440b9386">Hans Muller&#39;s article</a>.</p><p>There is no need to apply those to <a href="https://github.com/EdsonBueno/adaptive_bottom_nav_sample/blob/master/lib/custom/cupertino_bottom_navigation_scaffold.dart">CupertinoBottomNavigationScaffold</a>, since the lazy building is how it already works and the animation is a recommendation of the <a href="https://material.io/components/bottom-navigation/#behavior">Material Design&#39;s specification</a>.</p><p>If you want to see this bottom navigation structure applied to a real-world scenario with named routes, check out the article below.</p><p><a href="https://medium.com/better-programming/spotless-routing-and-navigation-in-flutter-995c647b9258">Spotless Routing and Navigation in Flutter</a></p><h3>Like what you read?</h3><p>If you want more in-depth articles like this, leave your e-mail <a href="https://edsonbueno.us4.list-manage.com/subscribe?u=344054ac1436a4189f9b824fd&amp;id=08a7d84462">here</a> and stay up to date with what I write.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a48bdd5fed4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/bottom-navigate-like-the-pros-in-flutter-8a48bdd5fed4">Bottom Navigate Like the Pros in Flutter</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spotless Routing and Navigation in Flutter]]></title>
            <link>https://medium.com/better-programming/spotless-routing-and-navigation-in-flutter-995c647b9258?source=rss-6de0af483df------2</link>
            <guid isPermaLink="false">https://medium.com/p/995c647b9258</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Edson Bueno]]></dc:creator>
            <pubDate>Thu, 23 Jan 2020 07:00:00 GMT</pubDate>
            <atom:updated>2020-12-09T09:43:09.543Z</atom:updated>
            <content:encoded><![CDATA[<h4>What’s the best way to handle routing and navigation in your code? Here’s a spotless solution you should give a try</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKrUSPP0IlhkW3oZs6drwg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bogdan_karlenko?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Bogdan Karlenko</a> on <a href="https://unsplash.com/s/photos/routes?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Intro</h3><p>As soon as you’ve finished studying the basics of Flutter and start working on your first projects, you’ll find yourself asking:</p><p>“What’s the best way I can handle routing and navigation?”</p><p>“Should I use named routes? Should I use a package?”</p><p>No, I’m not here to say “it depends on your needs.”</p><p>I work at a software <em>service</em> company, and as such, we develop many apps a year. That puts a demand on finding solutions that fit the largest number of different projects.</p><p>If you’ve done native mobile development, you know that routing always becomes a serious matter. Whenever I’m around iOSers, it’s five minutes before we’re discussing routers, coordinators, flows, and their pros and cons. With Androiders, it’s exactly the same — just replace the terms with Jetpack Navigation, Cicerone or FragNav. It seems like no one is ever completely satisfied with it.</p><p>If Flutter is your first foray into the mobile world, remember these words: This won’t be the last time you talk about routing strategies.</p><p>And before you get hopeless about it, just give me a chance to show you how I’ve been doing it.</p><p>I’m completely satisfied and I think you will be too.</p><p>Have you ever taken time to think about how navigation is typically made on the web?</p><p>I’m not talking about how it’s developed or anything like that — I’m interested in your experience as a website user or RESTful API consumer.</p><p>URLs are typically designed around resources, with a resource being a collection or a single item. For example:</p><p>Want to access a list of movies? Go to ${yourFavoriteMovieWebsite}/movies.</p><p>Want to see more details about a specific movie you found on the list? Go to ${yourFavoriteMovieWebsite}/movies/:picked_movie_id.</p><p>Did you notice the parametrized ID? That’s a path param or URL param.</p><p>What about seeing only the movies released in 2020? No problem, just pass in a query param called releaseYear to the first endpoint:</p><p>${yourFavoriteMovieWebsite}/movies?releaseYear=2020</p><p>By the way, that part of the URL containing the parameter, starting with the question mark, is what we call a query string.</p><p>Further reading: <a href="https://restfulapi.net/resource-naming/">REST Resource Naming</a>.</p><h3>What if We Could Do the Same With Our Apps?</h3><p>“Why would I want to do such a thing?”</p><p>Apart from it being amazingly intuitive and organized, we’re just one step behind being ready for deep links.</p><p>“Deep links?”</p><p>Have you ever opened a link on your phone that, instead of opening a web page, opens a specific page of an app?</p><p>Another good example is when you receive a push notification from a messenger app and tapping on it, it takes you to that specific conversation screen.</p><p>That’s what deep linking is all about. That’s also all we’re saying about it for today — it will have an article of its own soon.</p><p>My point is this: If we’re going to think of URL paths to our pages sooner or later, why not do it from the beginning? Even if you don’t have any intention of supporting deep links in your project, this is still the most well-established way of organizing routes.</p><p>To showcase today’s article, I decided we needed to work on a real app. To make it possible, I spent some time looking for free HTTP APIs, that’s when I found the great <a href="https://breakingbadapi.com/">Breaking Bad API</a>.</p><p>It provides us with a collection of information on the Breaking Bad and Better Call Saul TV Shows. Our app, though, is restricted to Breaking Bad characters and its remarkable quotes.</p><p>That settled, I found myself with the most challenging task of it all. Deciding what the app’s name would be!</p><h3>The Breaking Bapp Was Born</h3><p>Don’t worry about my marketer skills — I don’t intend to follow that career! Also, I promise you I’ll do my best to keep the “breaking” part only in the name.</p><figure><img alt="Breaking Bapp walkthrough" src="https://cdn-images-1.medium.com/max/250/0*agbghXH5L04DM0-R.gif" /><figcaption>Breaking Bapp walkthrough</figcaption></figure><h3>Thinking in Resources</h3><p>We already stated that we should design our paths around the resources we’re providing. Can you imagine what the URLs would look like if we were talking about a website? I did that exercise:</p><ul><li>List of characters: characters</li><li>Details of a single character: characters/:character_id</li><li>List of quotes: quotes</li><li>Details of a quote author: quotes/authors?name=:quote_author_name</li></ul><p>The last one is the trickiest. Maybe you’re wondering why name is a query param instead of a path param, or why we aren’t using the quote’s author ID instead of their name.</p><p>To answer that, let me first show you a quote’s JSON object retrieved from the API:</p><pre>{<br>   &quot;quote_id&quot;:1,<br>   &quot;quote&quot;:&quot;I am not in danger, Skyler. I am the danger!&quot;,<br>   &quot;author&quot;:&quot;Walter White&quot;<br>}</pre><p>Notice that we don’t have the ID of the author, just its name. Since name isn&#39;t a reliable unique identifier and path params are recommended for unique identifiers, the best thing we can do is thinking as if we&#39;re querying the author&#39;s resource.</p><p>By designing it like this, I can teach you how to work with query strings as we go.</p><p>It’s important to mention, for those of you who are not Breaking Bad fans, that a quote author is nothing but a character of the show. So, to obtain this info, we just need to use the character details endpoint — fortunately, the API allows us to find a character by its name instead of its ID.</p><h3>How Does Navigation Work in Flutter?</h3><p>Navigating is nothing but the simple act of transitioning to a new full-screen widget, which we call <em>a page</em> or <em>a screen</em>. To do so, we need to wrap this new widget inside a <a href="https://api.flutter.dev/flutter/widgets/Route-class.html">Route</a> object, that describes how the transition should happen, and push it to a <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a>. There are two ways to do this, by default.</p><h4><strong>First method</strong></h4><p>Give the <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a> a <a href="https://api.flutter.dev/flutter/widgets/Route-class.html">Route</a> object.</p><p>Bringing it to the Breaking Bapp, this is how it would look like for the onTap callback of the character’s list:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e9ef5f6b5ada4202452665334765fbd/href">https://medium.com/media/8e9ef5f6b5ada4202452665334765fbd/href</a></iframe><p>(Pro) Extremely easy to learn;</p><p>(Pro) Strongly typed;</p><p>(Con) Leads to lots of code duplication if you need to navigate to the same screen in many parts of your app;</p><h4><strong>Second method, a.k.a. named routes</strong></h4><p>Give the <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a> a route name and a generic argument (optional), which will be delivered to a function that maps these two to a <a href="https://api.flutter.dev/flutter/widgets/Route-class.html">Route</a>.</p><p>You need to write that function by yourself and use it as the <a href="https://api.flutter.dev/flutter/material/MaterialApp/onGenerateRoute.html">onGenerateRoute</a> of the <a href="https://api.flutter.dev/flutter/material/MaterialApp-class.html">MaterialApp</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf42601a0289ae89d24843234c94d7a6/href">https://medium.com/media/bf42601a0289ae89d24843234c94d7a6/href</a></iframe><p>(Con) Not as easy to learn as the first method.</p><p>(Pro) Although it looks more verbose, it is actually the recommended approach, because we keep our page’s instantiation centralized, avoiding code duplication.</p><p>If we take a closer look, the named route approach is relatively close to the web-thing we’re trying to accomplish. The only difference is that on the web, we wouldn’t need this argument object (the third param of the <a href="https://api.flutter.dev/flutter/widgets/Navigator/pushNamed.html">Navigator.pushNamed</a>), as we would be able to pass every parameter we need <em>inside</em> the route name, either as path param or as a query param.</p><p>We want to do this: Navigator.of(context).pushNamed(&#39;characters/${character.id}&#39;);</p><p>Instead of this: Navigator.of(context).pushNamed(&#39;character-details&#39;, arguments: character.id);</p><p>However, if you try to do this right away, it will give you a headache. Inside your <a href="https://api.flutter.dev/flutter/material/MaterialApp/onGenerateRoute.html">onGenerateRoute</a> function, you would need a way to wildcard the character&#39;s ID, so that characters/11 and characters/22 would take to the same route, just with different arguments. Another problem is having to strip and parse whatever comes after the question mark as query parameters.</p><h3><a href="https://pub.dev/packages/fluro#-readme-tab-">Fluro</a> Package to the Rescue</h3><p>According to them (and I’m inclined to agree), Fluro is:</p><blockquote><em>The brightest, hippest, coolest router for Flutter.</em></blockquote><p>Among several features, I would highlight:</p><ul><li>Wildcard parameter matching</li><li>Querystring parameter parsing</li></ul><p>We found our guy!</p><p>For our starting point, I built a version of the Breaking Bapp using the first routing method (without named routes), from which we’ll evolve to an elegant solution using Fluro.</p><p>Don’t worry about how I made the HTTP calls or what is the state management approach. I’ve managed to keep things as simple as possible so that it won’t take the focus of the navigation and routing.</p><p>To cover a scenario with multiple <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a>s, we have a bottom navigation menu structure.</p><p>I suggest you check out the starting-point branch of the <a href="https://github.com/EdsonBueno/breaking_bapp">Breaking Bapp&#39;s GitHub repository</a> and get relatively comfortable with it for a better learning experience.</p><h3>Step-by-step on Migrating to Fluro</h3><h4>1. Install Fluro</h4><p>The article is based on version 1.7.8.</p><p>Please, <strong>don’t use a newer version</strong> until you’re finished with all the steps. I can’t state how important that is.</p><p><a href="https://pub.dev/packages/fluro#-installing-tab-">https://pub.dev/packages/fluro#-installing-tab-</a></p><h4>2. Set up your routes</h4><p>The main Fluro’s class is called <a href="https://pub.dev/documentation/fluro/latest/fluro/FluroRouter-class.html">FluroRouter</a>. We’ll use it for everything we need to do, except for pushing pages, as we’ll continue to use the <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a> for that. You don’t need to instantiate it by yourself, as Fluro already made an instance available to us as a static variable, simply accessed by <a href="https://pub.dev/documentation/fluro/latest/fluro/FluroRouter/appRouter.html">FluroRouter.appRouter</a>.</p><p>First things first, we’ll start using a <a href="https://pub.dev/documentation/fluro/latest/fluro/FluroRouter-class.html">FluroRouter</a>’s function called <a href="https://pub.dev/documentation/fluro/latest/fluro/FluroRouter/define.html">define</a>, which serves the purpose of, guess what, <em>defining</em> a route. It takes in three arguments:</p><ul><li>A String representing the route’s path along with its expected <em>path</em> parameters. The query ones don’t need to be specified ahead.</li><li>A handler object which holds the page’s widget builder.</li><li>An optional <a href="https://pub.dev/documentation/fluro/latest/fluro/TransitionType-class.html">TransitionType</a>, just in case you want to change the default route transition.</li></ul><p>I did all my routing set up inside the main function (main.dart), and I suggest you do the same.</p><p>Read the Gist below carefully. I made an effort to comment everything you need to know.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/177fda5f1cba4de2e06b9049b63ca7fe/href">https://medium.com/media/177fda5f1cba4de2e06b9049b63ca7fe/href</a></iframe><h4>3. Link your router to your navigators</h4><p>Now we have a special little guy called <a href="https://pub.dev/documentation/fluro/latest/fluro/FluroRouter/appRouter.html">FluroRouter.appRouter</a> that knows how to handle all our web-like named routes. But we haven&#39;t plugged it anywhere. Because of that, when we <a href="https://api.flutter.dev/flutter/widgets/Navigator/pushNamed.html">Navigator.pushNamed</a> something, it still won&#39;t use all the setup we just did in the previous step.</p><p>Do you remember the <a href="https://api.flutter.dev/flutter/material/MaterialApp/onGenerateRoute.html">MaterialApp.onGenerateRoute</a> constructor parameter? We&#39;ve talked about it briefly when discussing named routes. We need to provide it with a function that receives the pushed route settings and uses it to build a concrete <a href="https://api.flutter.dev/flutter/widgets/Route-class.html">Route</a>. Guess who has one of these? Yes, the <a href="https://pub.dev/documentation/fluro/latest/fluro/FluroRouter/appRouter.html">FluroRouter.appRouter</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1971235be98ee9235006d60568311bec/href">https://medium.com/media/1971235be98ee9235006d60568311bec/href</a></iframe><p>Now, every time we navigate using our <em>root</em> <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a>, everything works just fine.</p><p><strong>“What do you mean by <em>root</em> Navigator?”</strong></p><p>By default, inside <a href="https://api.flutter.dev/flutter/material/MaterialApp-class.html">MaterialApp</a>, we&#39;re given a <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a> to push and pop our pages widgets, and this is the one we&#39;ve just linked with our <a href="https://pub.dev/documentation/fluro/latest/fluro/FluroRouter-class.html">FluroRouter</a>. But if your navigation structure is more complicated than that, for example if you use a <a href="https://material.io/components/bottom-navigation/">bottom navigation component</a>, you probably have more than one <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a>. We need to link those to Fluro as well. Fortunately that&#39;s the Breaking Bapp&#39;s scenario!</p><p><strong>“How can I make Fluro work with multiple </strong><a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html"><strong>Navigator</strong></a><strong>s?&quot;</strong></p><p><strong>Short answer</strong>: The <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a>‘s constructor also has an <a href="https://api.flutter.dev/flutter/widgets/Navigator/onGenerateRoute.html">onGenerateRoute</a>. Just give it the same FluroRouter.appRouter.matchRoute(context, settings.name, routeSettings: settings).route everywhere you instantiate a new <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a> in your code, use the <a href="https://api.flutter.dev/flutter/widgets/Navigator/initialRoute.html">initialRoute</a> parameter for changing its initial route, and skip to our fourth step.</p><p><strong>Long answer</strong>: For this, I’m going to show you how I did it in the Breaking Bapp’s bottom navigation.</p><p>If you haven’t followed my <a href="https://medium.com/swlh/bottom-navigate-like-the-pros-in-flutter-8a48bdd5fed4">latest article</a>, it won’t be easy for you to understand what’s going on. If that’s the case, I strongly suggest you be satisfied with the short answer and skip to the fourth step. I promise you there will be no losses!</p><p><strong>3.1. Linking your router to your additional navigators</strong></p><p>Our code has a class called <a href="https://github.com/EdsonBueno/breaking_bapp/blob/starting-point/lib/presentation/common/bottom_navigation/bottom_navigation_tab.dart">BottomNavigationTab</a> that holds all the dependencies for building our app&#39;s bottom navigation flows. That includes the item to be displayed in the menu, the <a href="https://api.flutter.dev/flutter/widgets/GlobalKey-class.html">GlobalKey</a> it should use for that specific tab&#39;s <a href="https://api.flutter.dev/flutter/widgets/Navigator-class.html">Navigator</a>, and the initial page builder for each. The initialPageBuilder was useful once when we were instantiating the routes ourselves (by using the first navigation method). But now that we&#39;re using named routes, we don&#39;t like page builders anymore, just route names, as Fluro is the one building things now.</p><p>Here’s the diff:</p><pre>class BottomNavigationTab {<br>    const BottomNavigationTab({<br>        @required this.bottomNavigationBarItem,<br>        @required this.navigatorKey,<br>-       @required this.initialPageBuilder,<br>+       @required this.initialRouteName,<br>    }) : assert(bottomNavigationBarItem != null),<br>       assert(navigatorKey != null),<br>-      assert(initialPageBuilder != null);<br>+      assert(initialRouteName != null);<br> <br>    final BottomNavigationBarItem bottomNavigationBarItem;<br>    final GlobalKey&lt;NavigatorState&gt; navigatorKey;<br>-   final WidgetBuilder initialPageBuilder;<br>+   final String initialRouteName;<br>}</pre><p>As we just changed the BottomNavigationTab&#39;s definition, we need to fix the place we&#39;re instantiating it:</p><pre>class HomeScreen extends StatefulWidget {<br>  <a href="http://twitter.com/override">@override</a><br>  _HomeScreenState createState() =&gt; _HomeScreenState();<br>}</pre><pre>class _HomeScreenState extends State&lt;HomeScreen&gt; {<br>  final List&lt;BottomNavigationTab&gt; _bottomNavigationTabs = [<br>    BottomNavigationTab(<br>      bottomNavigationBarItem: BottomNavigationBarItem(<br>        title: const Text(&#39;Characters&#39;),<br>        icon: Icon(Icons.people),<br>      ),<br>      navigatorKey: GlobalKey&lt;NavigatorState&gt;(),<br>-     initialPageBuilder: (_) =&gt; CharacterListPage(),<br>+     initialRouteName: &#39;characters&#39;,<br>    ),<br>    BottomNavigationTab(<br>      bottomNavigationBarItem: BottomNavigationBarItem(<br>        title: const Text(&#39;Quotes&#39;),<br>        icon: Icon(Icons.format_quote),<br>      ),<br>      navigatorKey: GlobalKey&lt;NavigatorState&gt;(),<br>-     initialPageBuilder: (_) =&gt; QuoteListPage(),<br>+     initialRouteName: &#39;quotes&#39;,<br>    )<br>  ];</pre><pre><a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) =&gt; AdaptiveBottomNavigationScaffold(<br>        navigationBarItems: _bottomNavigationTabs,<br>      );<br>}</pre><p>There are two more places left, both inside the material_bottom_navigation_scaffold.dart, as that’s where we&#39;re subclassing and instantiating the above BottomNavigationTab.</p><pre>class _MaterialBottomNavigationTab extends BottomNavigationTab {<br>  const _MaterialBottomNavigationTab({<br>    <a href="http://twitter.com/required">@required</a> BottomNavigationBarItem bottomNavigationBarItem,<br>    <a href="http://twitter.com/required">@required</a> GlobalKey&lt;NavigatorState&gt; navigatorKey,<br>-   <a href="http://twitter.com/required">@required</a> WidgetBuilder initialPageBuilder,<br>+   <a href="http://twitter.com/required">@required</a> String initialRouteName,<br>    <a href="http://twitter.com/required">@required</a> this.subtreeKey,<br>  })  : assert(bottomNavigationBarItem != null),<br>        assert(subtreeKey != null),<br>-       assert(initialPageBuilder != null),<br>+       assert(initialRouteName != null),<br>        assert(navigatorKey != null),<br>        super(<br>          bottomNavigationBarItem: bottomNavigationBarItem,<br>          navigatorKey: navigatorKey,<br>-         initialPageBuilder: initialPageBuilder,<br>+         initialRouteName: initialRouteName,<br>        );<br> <br>  final GlobalKey subtreeKey;<br>}</pre><pre>void _initMaterialNavigationBarItems() {<br>  materialNavigationBarItems.addAll(<br>    widget.navigationBarItems<br>        .map(<br>          (barItem) =&gt; _MaterialBottomNavigationTab(<br>            bottomNavigationBarItem: barItem.bottomNavigationBarItem,<br>            navigatorKey: barItem.navigatorKey,<br>            subtreeKey: GlobalKey(),<br>-           initialPageBuilder: barItem.initialPageBuilder,<br>+           initialRouteName: barItem.initialRouteName,<br>          ),<br>        )<br>        .toList(),<br>  );<br>}</pre><p>Finally, it’s time to ensure that our additional navigators delegates its route generation to Fluro, as well as using the newest initialRouteName of the BottomNavigationTab. I&#39;m using different bottom navigation menus for Android and iOS, so I needed to make that change in two files:</p><ol><li>material_bottom_navigation_scaffold.dart</li></ol><pre>Widget _buildPageFlow(<br>  BuildContext context,<br>  int tabIndex,<br>  _MaterialBottomNavigationTab item,<br>) {<br>  final isCurrentlySelected = tabIndex == widget.selectedIndex;<br> <br>  // We should build the tab content only if it was already built or<br>  // if it is currently selected.<br>  _shouldBuildTab[tabIndex] =<br>      isCurrentlySelected || _shouldBuildTab[tabIndex];<br> <br>  final Widget view = FadeTransition(<br>    opacity: _animationControllers[tabIndex].drive(<br>      CurveTween(curve: Curves.fastOutSlowIn),<br>    ),<br>    child: KeyedSubtree(<br>      key: item.subtreeKey,<br>      child: _shouldBuildTab[tabIndex]<br>          ? Navigator(<br>              // The key enables us to access the Navigator&#39;s state inside the<br>              // onWillPop callback and for emptying its stack when a tab is<br>              // re-selected. That is why a GlobalKey is needed instead of<br>              // a simpler ValueKey.<br>              key: item.navigatorKey,<br>-             // Since this isn&#39;t the purpose of this sample, we&#39;re not using<br>-             // named routes. Because of that, the onGenerateRoute callback<br>-             // will be called only for the initial route.<br>-             onGenerateRoute: (settings) =&gt; MaterialPageRoute(<br>-               settings: settings,<br>-               builder: item.initialPageBuilder,<br>-             ),<br>+             initialRoute: item.initialRouteName,<br>+             // RouteFactory is nothing but an alias of a function that takes<br>+             // in a RouteSettings and returns a Route&lt;dynamic&gt;, which is<br>+             // the type of the onGenerateRoute parameter.<br>+             // We registered one of these in our main.dart file.<br>+             onGenerateRoute: FluroRouter.appRouter<br>+                 .matchRoute(context, settings.name, routeSettings: settings)<br>+                 .route,<br>            )<br>          : Container(),<br>    ),<br>  );<br> <br>  if (tabIndex == widget.selectedIndex) {<br>    _animationControllers[tabIndex].forward();<br>    return view;<br>  } else {<br>    _animationControllers[tabIndex].reverse();<br>    if (_animationControllers[tabIndex].isAnimating) {<br>      return IgnorePointer(child: view);<br>    }<br>    return Offstage(child: view);<br>  }<br>}</pre><p>2. cupertino_bottom_navigation_scaffold.dart</p><pre>Widget build(BuildContext context) =&gt; CupertinoTabScaffold(<br>      // As we&#39;re managing the selected index outside, there&#39;s no need<br>      // to make this Widget stateful. We just need pass the selectedIndex to<br>      // the controller every time the widget is rebuilt.<br>      controller: CupertinoTabController(initialIndex: selectedIndex),<br>      tabBar: CupertinoTabBar(<br>        items: navigationBarItems<br>            .map(<br>              (item) =&gt; item.bottomNavigationBarItem,<br>            )<br>            .toList(),<br>        onTap: onItemSelected,<br>      ),<br>      tabBuilder: (context, index) {<br>        final barItem = navigationBarItems[index];<br>        return CupertinoTabView(<br>          navigatorKey: barItem.navigatorKey,<br>-         onGenerateRoute: (settings) =&gt; CupertinoPageRoute(<br>-           settings: settings,<br>-           builder: barItem.initialPageBuilder,<br>-         ),<br>+         onGenerateRoute: (settings) {<br>+           // The [Navigator] widget has a initialRoute parameter, which<br>+           // enables us to define which route it should push as the initial<br>+           // one. See [MaterialBottomNavigationScaffold] for more details.<br>+           //<br>+           // The problem is that in the Cupertino version, we&#39;re not<br>+           // instantiating the [Navigator] ourselves, instead we&#39;re<br>+           // delegating it to the CupertinoTabView, which doesn&#39;t provides<br>+           // us with a way to set the initialRoute name. The best<br>+           // alternative I could find is to &quot;change&quot; the route&#39;s name of<br>+           // our RouteSettings to our BottomNavigationTab&#39;s initialRouteName<br>+           // when the onGenerateRoute is being executed for the initial<br>+           // route.<br>+           var routeSettings = settings;<br>+           if (settings.name == &#39;/&#39;) {<br>+             routeSettings =<br>+               settings.copyWith(name: barItem.initialRouteName);<br>+             );<br>+           } <br>+           return FluroRouter.appRouter<br>+               .matchRoute(<br>+                 context,<br>+                 routeSettings.name,<br>+                 routeSettings: routeSettings,<br>+               )<br>+               .route;<br>+         },<br>        );<br>      },<br>    );</pre><h4>4. Navigate</h4><p>Everything we’ve done by now was about being prepared to handle any incoming web-like named routes, but we’re still not using them. We need to stop using <a href="https://api.flutter.dev/flutter/widgets/Navigator/push.html">Navigator.push</a> and start using <a href="https://api.flutter.dev/flutter/widgets/Navigator/pushNamed.html">Navigator.pushNamed</a>. There are two places for changing that:</p><ul><li>When selecting a character on the list.</li></ul><p>character_list_page.dart</p><pre>- Navigator.push(<br>-   context,<br>-   MaterialPageRoute(<br>-     builder: (context) =&gt; CharacterDetailPage(<br>-      id: character.id,<br>-     ),<br>-   ),<br>+ Navigator.of(context).pushNamed(<br>+   &#39;characters/${character.id}&#39;,<br>  );</pre><ul><li>When selecting a quote’s author on the list.</li></ul><p>quote_list_page.dart</p><pre>Navigator.of(<br>    context,<br>    rootNavigator: true,<br>- ).push(<br>-   MaterialPageRoute(<br>-     fullscreenDialog: true,<br>-     builder: (context) =&gt; CharacterDetailPage(<br>-       name: quote.authorName,<br>-     ),<br>-   ),<br>+ ).pushNamed(<br>+   &#39;quotes/authors?name=${quote.authorName}&#39;,<br>  );</pre><p>We’re all done!</p><h4>Side note</h4><p>I once read someone arguing that with Fluro, we’re not able to pass <em>complex objects</em> directly from one page to another. Although we can find obscure ways to do that, I don’t advise on doing so.</p><p>I firmly believe that we shouldn’t be passing complex objects around. An alternative I prefer is giving the object an id and storing it in your data layer. That way, we can pass only its id between pages.</p><h3>Bonus</h3><p>You may have noticed that the route names are duplicated across the code. This isn’t a recommended practice at all. It served the purpose of improving the article’s readability, but I don’t want you to do that anywhere else. For inspiration on how to extract it, check out the master branch.</p><h3>Useful Links</h3><ul><li><a href="https://github.com/EdsonBueno/breaking_bapp">GitHub Repository</a></li><li><a href="https://medium.com/swlh/bottom-navigate-like-the-pros-in-flutter-8a48bdd5fed4">Bottom Navigate Like the Pros in Flutter</a></li><li><a href="https://breakingbadapi.com/">Breaking Bad API</a></li><li><a href="https://pub.dev/packages/fluro">Fluro Package</a></li><li><a href="https://restfulapi.net/resource-naming/">REST Resource Naming</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=995c647b9258" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/spotless-routing-and-navigation-in-flutter-995c647b9258">Spotless Routing and Navigation 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>