<?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 Lulupointu on Medium]]></title>
        <description><![CDATA[Stories by Lulupointu on Medium]]></description>
        <link>https://medium.com/@lucasdelsol01?source=rss-940c22f73489------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*63Oh7JFKvUxrnbvM</url>
            <title>Stories by Lulupointu on Medium</title>
            <link>https://medium.com/@lucasdelsol01?source=rss-940c22f73489------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 13:36:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucasdelsol01/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[How to create a custom lint in Flutter with custom_lints]]></title>
            <link>https://lucasdelsol01.medium.com/how-to-create-a-custom-lint-in-flutter-with-custom-lints-5c369293b387?source=rss-940c22f73489------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c369293b387</guid>
            <category><![CDATA[lint]]></category>
            <category><![CDATA[quickfix]]></category>
            <category><![CDATA[custom-lint]]></category>
            <category><![CDATA[ast]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Lulupointu]]></dc:creator>
            <pubDate>Wed, 13 Jul 2022 15:24:16 GMT</pubDate>
            <atom:updated>2022-07-13T15:24:16.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAJLzYIoutyZQ4f-hT_02A.png" /></figure><h3>Getting started with custom_lints</h3><p>When the custom_lints package did not exist, one had to painfully connect to the dart analyser: a terrible and tedious DX. Fortunately, that’s not the case anymore.</p><p>The easiest way to get start is to follow the README of <a href="https://pub.dev/packages/custom_lint">custom_lints on pub.dev</a>. You should have your first lint showing in less than 10 minutes !</p><p>Tips to work with the custom_lints package:</p><ul><li>Once you make a change to your lint, if it does not restart in the project where you visualize your lint run flutter pub get and wait for them to appear</li><li>prints are your best friends. They will show up in the custom_lints.log file (which appears at the same level as where your pubspec.yaml is). I would advise you to never delete this file while working on your project since it can take some time before it first appears.</li></ul><h3>Create your first custom lint in Flutter</h3><p>While the custom_lints package allows you to get started, it only provides you with a blank canvas. If you try to do anything, you will soon find that you have to learn to use paint, brushes and more - all things which are not included in the package. Let’s see how to start walking this new world of great possibilities through an example:</p><p><strong>&gt; Let’s create a lint which warns the user not to assign </strong><strong>List but to use </strong><strong>IList instead.</strong></p><blockquote><em>IList is as immutable equivalent to </em><em>List from the </em><a href="https://pub.dev/packages/fast_immutable_collections"><em>fast_immutable_collections package</em></a><em>. This package is awesome and will remove all the untraceable errors that classic </em><em>Lists lets slip by.</em></blockquote><p><em>Note: The best way to learn the concept which follow is practice. I would advise you setup custom_lint and follow along. </em><a href="https://github.com/lulupointu/lint_no_list_tutorial"><em>Here is a repo from which to start</em></a><em> (where custom_lint is already setup). Every problem is separated in digestible steps with first the explanation of what we are trying to do and then the solution. The best way to read this article is to try each step before reading the solution.</em></p><p><strong>Implementation plan:</strong></p><ul><li>Create and place the lint</li><li>What is the AST tree and how to get every variable declaration?</li><li>Check for variable type</li><li>Lint creation and placement from variable Element</li><li>Implement lint quick fix</li></ul><h3>Create and place the lint</h3><p>In this first part, we will try to place the lint under every variable to which a List is assigned. Here is an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*ktpVWbBlZXkvouOshxQa_g.png" /></figure><h3>What is the AST tree and how to get every variable declaration?</h3><p>The first step to creating a lint is to parse the code. In each file, the code is represented by two main trees:</p><ul><li>The Element tree</li><li>The AST tree</li></ul><p>The Element tree represents things that are declared with a name (e.g. classes, variables, methods, …) while the AST tree represents the structure of the code. Here is a concrete example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVJjYCX1U2FzsvjKkaZwFg.png" /></figure><p>What is important to remembers is that the AST tree is more complete but harder to parse. When you can, stick with the Element tree but if you really need, switch to AST.</p><p>In our case, we will need to have the Expression in order to be able to wrap it with IList (see next chapter). Therefore we will choose the AST tree.</p><p>In order to parse those trees, the easiest way is to use Visitors, which are classes with built-in method to detect what they are visiting. In particular, the RecursiveAstVisitor (or RecursiveElementVisitor) are particularly useful. In our case, we want to override the visitVariableDeclaration method of RecursiveAstVisitor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58f4f9d7554ea5494872167bf005211f/href">https://medium.com/media/58f4f9d7554ea5494872167bf005211f/href</a></iframe><p>You can then use this Visitor to parse the current file inside the custom_lints getLints method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41a248c6241ee159171c51e202afe295/href">https://medium.com/media/41a248c6241ee159171c51e202afe295/href</a></iframe><p>The <em>getLints method is generative. If this does not sound familiar, you might want to check out </em><a href="https://www.youtube.com/watch?v=TF-TBsgIErY"><em>the video on this topic from the Flutter team</em></a></p><p>So far so good, we have gathered all the variable declaration in the file!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*OueXYDzq8LgXCTyt.gif" /></figure><h3>Check for variable type</h3><p>Next step is to filter only the VariableDeclarations that are associated to list. To do so we need to:</p><ul><li>Use VariableDeclaration.declaredElement.type to get a special representation of the type of the variable</li><li>Import the <a href="https://pub.dev/packages/source_gen">source_gen package</a> and use the TypeChecker class</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abfb294b9028a8683c81acbebd94a7df/href">https://medium.com/media/abfb294b9028a8683c81acbebd94a7df/href</a></iframe><h3>Create the lint and place it at the right location</h3><p>Finally, we can start building our Lint. The Lint class is fairly easy to use, the only challenge is to find specify the location of our lint. What you need to remember is that once you have any Element, you will be able to use its nameOffset and nameLength:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfacf45454a7a3ae42dce8278e3fce49/href">https://medium.com/media/cfacf45454a7a3ae42dce8278e3fce49/href</a></iframe><p>Here you go, now if we start the project in which our lint is imported we should see is appear where we want:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*ktpVWbBlZXkvouOshxQa_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*nvF6MuMKU3u4gcMv.gif" /></figure><p>Now that you have successfully communicated the developers what <strong>not</strong> to do, let’s show them what to do with <strong>quick fixes</strong>.</p><h3>Implement lint quick fix</h3><p>Quick fixes are suggestions integrated in the editor which allows you to fix a lint with one click:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vnDJy1uAGlmeCT_DiTFDg.gif" /></figure><p>To implement quick fixes, you have to use the getAnalysisErrorFixes parameter of the Lint we just created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00d99a4e5ff2389784522f8fbd316047/href">https://medium.com/media/00d99a4e5ff2389784522f8fbd316047/href</a></iframe><p>The two things we have to customize are:</p><ul><li>priority: A number ≥ 0 which states how much the lint is pertinent (the lower the most pertinent)</li><li>sourceChange which indicated which change to actually perform when the quick fix is clicked. You can easily build a sourceChange though a ChangeBuilder which has aChangeBuilder.sourceChange property.</li></ul><p>For some reason, change is <strong>not</strong> exported from the analyzer plugin so add an import to be able to export it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eca4662a89048699448f4c7830c1c197/href">https://medium.com/media/eca4662a89048699448f4c7830c1c197/href</a></iframe><p>To indicate the change you want to perform, use the changeBuilder.addDartFileEdit method (which is async: don’t forget to await it!). This method takes two parameters:</p><ul><li>path: the path to the file you want to edit, which will nearly always be the current one, accessible with: unit.libraryElement.source.fullName</li><li>buildFileEdit: a method which gives you a fileEditBuilder which you can use to make the changes in the file</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b302dafa1d3ca8cbf14a0f66c3238ba5/href">https://medium.com/media/b302dafa1d3ca8cbf14a0f66c3238ba5/href</a></iframe><p>fileEditBuilder is quite simple to use. The only challenge, as for the lint, it to know the position of what you want to replace. In our example we want to wrap the expression used to define our variable: This won’t be perfect and could be improved but will work well in most cases. The expression can be obtained from VariableDeclaration which we got in the first part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca722eeb84b5865317dba6497ec0fdbe/href">https://medium.com/media/ca722eeb84b5865317dba6497ec0fdbe/href</a></iframe><p>The last thing you might want to specify is a message letting the user know what the quick fix does:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67b675d53f7b1fde67b6f4294c70cf46/href">https://medium.com/media/67b675d53f7b1fde67b6f4294c70cf46/href</a></iframe><p>Go back to the project where you imported the lint and you should see and be able to apply the quick fix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vnDJy1uAGlmeCT_DiTFDg.gif" /></figure><p>Tada! We have created our first lint!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*iJS3GsIj8K5oUASG.gif" /></figure><h3>What you need to remember</h3><ul><li>Parse a file with RecursiveAstVisitor or RecursiveElementVisitor</li><li>Use TypeChecker from the <a href="https://pub.dev/packages/source_gen">source_gen package</a> to check types</li><li>Get the Element you need and use its nameOffset and nameLength to position your lint</li><li>VariableDeclaration is an AST node which represents a variable (in VariableDeclaration.declaredElement) and its associated expression (in VariableDeclaration.initializer)</li><li>Use ChangeBuilder (by importing package:analyzer_plugin/utilities/change_builder/change_builder_core.dart) to modify the file content through quick fixes</li></ul><h3>Lint implementation repo</h3><p><a href="https://github.com/lulupointu/lint_no_list_tutorial_solution">https://github.com/lulupointu/lint_no_list_tutorial_solution</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c369293b387" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Navigator 2.0 made simple: VRouter]]></title>
            <link>https://lucasdelsol01.medium.com/flutter-navigator-2-0-made-simple-vrouter-91d1495b3f56?source=rss-940c22f73489------2</link>
            <guid isPermaLink="false">https://medium.com/p/91d1495b3f56</guid>
            <category><![CDATA[flutter-navigator]]></category>
            <category><![CDATA[flutter-mobile-app]]></category>
            <category><![CDATA[flutter-plugin]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-web]]></category>
            <dc:creator><![CDATA[Lulupointu]]></dc:creator>
            <pubDate>Sun, 21 Feb 2021 10:40:57 GMT</pubDate>
            <atom:updated>2021-03-31T14:50:56.541Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Since it came out, the Navigator 2.0 API has been controversial. Many complained about its complicity and verbosity. This changes today with the introduction of a flutter package: <a href="https://pub.dev/packages/vrouter">vrouter</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRSNX2hner0xGXCjlVcr8A.png" /></figure><p><em>This article is up to date with VRouter ≥1.1</em></p><h3>VRouter basics</h3><p>VRouter is the widget handling the routing of your app. All you have to do is define the routes parameter to create your different routes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f478362c11060a516afcfbded0ff9842/href">https://medium.com/media/f478362c11060a516afcfbded0ff9842/href</a></iframe><ul><li>routes is a list of VRouteElement</li><li>VWidget is a VRouteElement mapping a path to a widget .</li></ul><h3>Navigate</h3><p>Navigation is the other side of the coin. Once your routes are defined, you want to be able to navigate programmatically.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9dc2c11045e503b50e77e9f30f32d10/href">https://medium.com/media/c9dc2c11045e503b50e77e9f30f32d10/href</a></iframe><h3>A Simple Example</h3><p>Now that you understood the basic, let’s build a simple app: the infamous book app from the medium article introducing Navigator 2.0.</p><p>The app is made of 3 routes:</p><ul><li>/books which displays the list of books</li><li>books/:title with :title being a path parameter being to be any string, and representing the name of a book.</li><li>/unknown which covers any unknown path</li></ul><h4>VRouter configuration</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ede74a245093ad7660e6efe613c66241/href">https://medium.com/media/ede74a245093ad7660e6efe613c66241/href</a></iframe><p>As you can see, we just translate the different path we talk about.</p><p><strong>Interesting things to note are:</strong></p><ul><li>A VWidgetcan have stackedRoutes, this is useful to created the paths you want. Here the path :title does not start with / and it is a subroute of the path /books so the matched path is /books/:title</li><li>VRouteRedirector is a special type of VRouteElement which allows to redirect easily. Note that the path in composed of a path parameter since it starts with :which has a regExp specified in parentheses: .+ allows us to match anything.</li><li>context.vRouter allows you to access VRouter data such as the path parameter</li></ul><h4>Navigating</h4><p>VRouterData holds every methods for the navigation as we saw, here we use push.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/911a8c1aaae11e9165155a55b9ba9dd2/href">https://medium.com/media/911a8c1aaae11e9165155a55b9ba9dd2/href</a></iframe><p>Note how we don’t start our path with /, which indicated that the given string should be appended to the current path to form the new url.</p><p>Also note how we have nothing to do for the pop event to be handled (when the appBar back button is pressed). This is because VRouter internally uses a specific algorithm to handle it, however this behavior could be overwritten.</p><h3><strong>Full code</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eee67a025d2200b66a11402574034570/href">https://medium.com/media/eee67a025d2200b66a11402574034570/href</a></iframe><h3>Learn more</h3><p>VRouter enable you to do way more than what we just saw, here are a few things which can easily be done:</p><ul><li>Change the default transition or specify specific transitions for specific routes</li><li>Nesting widgets (instead of stacking) by using another VRouteElement named VNester</li><li>Customize back button behavior</li><li>React to route changes (stop them, redirect, …)</li><li>Saving your widget state to restore it when the browser backward button is pressed</li></ul><p>To learn more about it, head over to<strong> </strong><a href="https://vrouter.dev/"><strong>vrouter.dev</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*S9oaRASlkIi0_Qfqabjylw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91d1495b3f56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter web: A complete example using simple_url_handler]]></title>
            <link>https://lucasdelsol01.medium.com/flutter-web-a-complete-example-using-simple-url-handler-517c2ced805a?source=rss-940c22f73489------2</link>
            <guid isPermaLink="false">https://medium.com/p/517c2ced805a</guid>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-navigation]]></category>
            <category><![CDATA[flutter-navigator]]></category>
            <category><![CDATA[url]]></category>
            <dc:creator><![CDATA[Lulupointu]]></dc:creator>
            <pubDate>Fri, 22 Jan 2021 16:59:29 GMT</pubDate>
            <atom:updated>2021-02-23T22:21:59.041Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article is part of a series aiming at making you a master of Navigator 2.0 while showing you that it is not as hard as people think. The other articles of this series are:</em></p><ul><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-101-for-mobile-dev-5094566613f6"><em>Flutter Navigator 2.0: 101 for mobile dev</em></a><em>: Where to start if you have no idea what navigator 2.0 is.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-nested-navigators-basics-2dab6c55010e"><em>Flutter Navigator 2.0 for mobile dev: Nested navigators basics</em></a><em>: How to nest the navigators, and the fix needed to avoid that they ruin your animations</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-transitions-1967b79aaa37"><em>Flutter Navigator 2.0 for mobile dev: Transitions</em></a><em>: How to implement Hero or Page route transitions with navigator 2.0</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-bloc-state-management-integration-3a180b4d25b3"><em>Flutter Navigator 2.0 for mobile dev: Bloc state management integration</em></a><em>: How to use navigator 2.0 and the bloc library</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-web-dev-url-handling-ffbbb9311219"><em>Flutter Navigator 2.0 for web dev: Url handling</em></a><em>: The basics of URL handling.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-web-url-handling-made-simple-with-simple-url-handler-702ffbaa7a0b"><em>Flutter web: URL handling made simple with simple_url_handler</em></a><em>: How to use the simple_url_handler package to manage the URL in flutter web easily.</em></li></ul><p>Navigator 2.0 received some negative feedback when it came out. However, today we will see how:</p><ul><li>Routing is not as hard as it looks.</li><li>Url handling is made very easy by the package <a href="https://pub.dev/packages/simple_url_handler">simple_url_handler</a></li></ul><h3>The app we will create</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*6Y5FSgu4_nC0Yco0zsZStw.gif" /></figure><h3><strong>App architecture</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rf9S2lQMbOrbTJCuhgRJaQ.png" /></figure><p>We will need 3 main widgets and 2 routers.</p><h3>The app state</h3><p>The state of the app will be stored in a ChangeNotifier provided by a ChangeNotifierProvider at the top of the app. Here is the app state class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13eaf9de63724320ab1e4055ff2bed08/href">https://medium.com/media/13eaf9de63724320ab1e4055ff2bed08/href</a></iframe><p>Three main attributes describe this class:</p><ul><li>selectedBottomNavigationBarIndex: 0 is the profile, and 1 is the settings</li><li>redirectFrom is set when the user tries to access profile or settings while not being allowed to. It hosts a InAppPages which is either Profile or Settings</li><li>isAuthenticated which is self-explanatory. The interesting part is that it is a setter method. Indeed when authenticating (i.e., setting isAuthenticated to true) we check if redirectedFrom has a value and if so, change selectedBottomNavigationBarIndex accordingly.</li></ul><h3>AuthenticationRouter</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fc6c3a019a3b7f1b8a1b5ded7f40195/href">https://medium.com/media/8fc6c3a019a3b7f1b8a1b5ded7f40195/href</a></iframe><p>As always with navigator 2.0, we create a Router widget, which will contain our RouterDelegate (which is basically its child).</p><p>We also create a RootBackButtonDispatcher because we cant to handle the AppBar back button.</p><p><strong>AuthenticationRouterDelegate</strong></p><p><em>In the build method</em>, we create a Navigator (to which we give a global key for page animations). The pages are MaterialPages containing either the AuthenticationWidget or the NestedRouterWidget. Note how we declarative decide if we want to show the NestedRouterWidget with the isAuthenticated boolean from our app state.</p><p><em>In the onPop method</em>, we set isAuthenticated to false if we pop on the AuthenticationWidget. This happens when we press the AppBar back button, for example.</p><p><em>The popRoute method</em> is triggered if we want to pop the AuthenticationWidget, in that case, we stop the application gracefully with the <a href="https://pub.dev/packages/move_to_background">move_to_background</a> package.</p><p>Note that we use obeservers: [HeroController()] because we need it to avoid breaking hero animations in the nested navigator. Since SimpleUrlHandler will create a navigator, this is a nested navigator, so we add this.</p><h3>NestedRouter</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65940596a433ea69ce2350cf02f7a123/href">https://medium.com/media/65940596a433ea69ce2350cf02f7a123/href</a></iframe><p>This nested delegate is pretty much the same as the authentication one. Note how easy it is to nest navigator, nothing special: nest them.</p><p>We create a BottomNavigationBar on top of our navigator so that it is shared between the two pages, and inside the navigator, we choose which Widget to display with the selectedBottomNavigationBarIndex.</p><p>Also, note how we return false in the onPopPage method. This is because we handle the pop in the AuthenticationRouterDelegate. Since we took priority in line 16, a pop event will first be triggered here, and then, if we return false, the next onPopPage event will be triggered (so in our case, the AuthenticationRouterDelegate one).</p><h3>Url Handling</h3><p>Concerning the URL it will be handled as follow:</p><ul><li>/profile when the user is on the ProfileWidget</li><li>/settings when the user is on the SettingsWidget</li><li>/login when the user is on the AuthenticationWidget</li><li>/login#profile when the user tries to access /profile but is not authenticated</li><li>/login#settings when the user tries to access /settings but is not authenticated</li></ul><p>This can be easily achieved thanks to the <a href="https://pub.dev/packages/simple_url_handler">simple_url_handler</a> package.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b3027b082bd73ca291d41605ce1e7df/href">https://medium.com/media/9b3027b082bd73ca291d41605ce1e7df/href</a></iframe><p>The first interesting part is happening line 21–22. Indeed, we add a listener to the app state, which will call SimpleUrlNotifier.of(context).notify any time the app state changes.</p><p>Then we must provide urlToAppState and appStateToUrl to the SimpleUrlHandler:</p><p>urlToAppState is called whenever the url is typed manually or the forward/backward button is pressed. When it is called, we parse the route location and modify our app state accordingly. Note that if the appState is updated, appStateToUrl is called thanks to what we just saw. So any redirection will update the url. Also, note that if that state can not be changed to a valid one, we SimpleUrlNotifier.of(context).notify() to update the url back to a valid one.</p><p>appStateToUrl is called when SimpleUrlNotifier.of(context).notify() is called or when the SimpleUrlHandler is built. Here we use our AppState class to determine what should be the corresponding url.</p><h3>Try it yourself</h3><p>You can find the code for this app <a href="https://github.com/lulupointu/simple_url_handler/tree/main/examples/complete_app">on github</a>. Play around with the code, and you will soon realize that navigator 2.0 is a beauty.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=517c2ced805a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter web: URL handling made simple with simple_url_handler]]></title>
            <link>https://lucasdelsol01.medium.com/flutter-web-url-handling-made-simple-with-simple-url-handler-702ffbaa7a0b?source=rss-940c22f73489------2</link>
            <guid isPermaLink="false">https://medium.com/p/702ffbaa7a0b</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[url]]></category>
            <category><![CDATA[flutter-navigator]]></category>
            <category><![CDATA[flutter-navigation]]></category>
            <category><![CDATA[flutter-web]]></category>
            <dc:creator><![CDATA[Lulupointu]]></dc:creator>
            <pubDate>Fri, 22 Jan 2021 09:44:15 GMT</pubDate>
            <atom:updated>2021-01-22T17:28:04.008Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article is part of a series aiming at making you a master of Navigator 2.0 while showing you that it is not as hard as people think. The other articles of this series are:</em></p><ul><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-101-for-mobile-dev-5094566613f6"><em>Flutter Navigator 2.0: 101 for mobile dev</em></a><em>: Were to start if you have no idea what navigator 2.0 is.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-nested-navigators-basics-2dab6c55010e"><em>Flutter Navigator 2.0 for mobile dev: Nested navigators basics</em></a><em>: How to nest the navigators, and the fix needed to avoid that they ruin your animations</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-transitions-1967b79aaa37"><em>Flutter Navigator 2.0 for mobile dev: Transitions</em></a><em>: How to implement Hero or Page route transitions with navigator 2.0</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-bloc-state-management-integration-3a180b4d25b3"><em>Flutter Navigator 2.0 for mobile dev: Bloc state management integration</em></a><em>: How to use navigator 2.0 and the bloc library</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-web-dev-url-handling-ffbbb9311219"><em>Flutter Navigator 2.0 for web dev: Url handling</em></a><em>: The basics of URL handling.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-web-a-complete-example-using-simple-url-handler-517c2ced805a"><em>Flutter web: A complete example using simple_url_handler</em></a><em>: A complete example, using everything seen above, to build the routing and url handling of a more complete app.</em></li></ul><p>Do you want to deliver a good experience to you web users without having to implement many methods ? This is what the<a href="https://pub.dev/packages/simple_url_handler"> <em>simple_url_handler</em></a> package is here for.</p><h3>What are we going to build?</h3><p>We are going to make the counter_app up-to-date by handling the url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*cOrPTCCGREiDsvdA.gif" /></figure><h3>The base counter app</h3><p>I suppose that you are familiar with this code but I want to emphases what you have to add.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e30c86ea07e0a0dd75d869cdab9bb0b/href">https://medium.com/media/5e30c86ea07e0a0dd75d869cdab9bb0b/href</a></iframe><h3>Url Handling</h3><p>To handle the url with the <a href="https://pub.dev/packages/simple_url_handler"><em>simple_url_handler</em></a> package we first have to import the package:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dae8feda99e830a1668463d9307073bf/href">https://medium.com/media/dae8feda99e830a1668463d9307073bf/href</a></iframe><p>The we need to focus on 2 widget:</p><ul><li>SimpleUrlHandler : used to map your app state and the url</li><li>SimpleUrlNotifier: used to notify SimpleUrlHandler that the url should be updated</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b43ea15c1a06da9b56ae301e77f7462/href">https://medium.com/media/1b43ea15c1a06da9b56ae301e77f7462/href</a></iframe><p>There is 2 important methods to implement: urlToAppState and appStateToUrl .</p><p><strong>urlToAppState:</strong> This method is called whenever the url is manually updated or when the user presses the forward/backward button. In our case:</p><ul><li>Line 4: We try to parse the url, new counter is null if the url is not in the form of ‘/int’</li><li>Line 5 to 8: if the new counter is valid (not null) and it’s different from our count value, we update our count value and call setState to update the UI</li><li>Line 9 to 13: This is really interesting, here the url is invalid, so we don’t change the count value, however we call SimpleNotifier.of(context).notify() to update the url back to a valid one.</li></ul><p><strong>appStateToUrl:</strong> This is called when SimpleNotifier.of(context).notify() is used or when the SimpleUrlHandler is first created. We need to return a RouteInformation where the location attribute will be our url.</p><h3>The entire code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b2ea5783c326c9ecf74e229dd1626c2/href">https://medium.com/media/6b2ea5783c326c9ecf74e229dd1626c2/href</a></iframe><p><strong>Note</strong> that usually we would want to call SimpleNotifier.of(context).notify() in the onPressed method in order to update the url, but since we are using setState our SimpleUrlHandler will be rebuilt and therefore appStateToUrl will be called automatically.</p><h3>Limitation</h3><p>There are 2 main limitations to this plugin:</p><ul><li>Since it uses navigator 2.0, you should use navigator 2.0 for routing as well</li><li>For the same reason, it is not compatible with the MaterialApp widget. You should instead use MaterialApp.router or use SimpleUrlHandler as you MaterialAppwidget. In our example we passed debugShowCheckedModeBanner: false for example.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=702ffbaa7a0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Navigator 2.0 for web dev: Url handling]]></title>
            <link>https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-web-dev-url-handling-ffbbb9311219?source=rss-940c22f73489------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffbbb9311219</guid>
            <category><![CDATA[flutter-navigator]]></category>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[flutter-navigation]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[url]]></category>
            <dc:creator><![CDATA[Lulupointu]]></dc:creator>
            <pubDate>Thu, 21 Jan 2021 15:06:17 GMT</pubDate>
            <atom:updated>2021-01-22T17:27:06.304Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article is part of a series aiming at making you a master of Navigator 2.0 while showing you that it is not as hard as people think. The other articles of this series are:</em></p><ul><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-101-for-mobile-dev-5094566613f6"><em>Flutter Navigator 2.0: 101 for mobile dev</em></a><em>: Were to start if you have no idea what navigator 2.0 is.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-nested-navigators-basics-2dab6c55010e"><em>Flutter Navigator 2.0 for mobile dev: Nested navigators basics</em></a><em>: How to nest the navigators, and the fix needed to avoid that they ruin your animations</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-transitions-1967b79aaa37"><em>Flutter Navigator 2.0 for mobile dev: Transitions</em></a><em>: How to implement Hero or Page route transitions with navigator 2.0</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-bloc-state-management-integration-3a180b4d25b3"><em>Flutter Navigator 2.0 for mobile dev: Bloc state management integration</em></a><em>: How to use navigator 2.0 and the bloc library</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-web-url-handling-made-simple-with-simple-url-handler-702ffbaa7a0b"><em>Flutter web: URL handling made simple with simple_url_handler</em></a><em>: How to use the simple_url_handler package to easily manage the url in flutter web.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-web-a-complete-example-using-simple-url-handler-517c2ced805a"><em>Flutter web: A complete example using simple_url_handler</em></a><em>: A complete example, using everything seen above, to build the routing and url handling of a more complete app.</em></li></ul><p>Url handling was one of the biggest promise of navigator 2.0. And by “url handling” I mean:</p><ul><li>Changing the state of your app updates the url</li><li>Changing your url changes your app state</li><li>The forward and backward button on a browser work</li></ul><p>In short: bringing the expected web experience to our app.</p><p>What you already know is that this is now possible, what you don’t know is <strong>how simple this is</strong>.</p><p><strong>Note</strong> that this article is NOT about routing. This is really important because flutter introduced us to routing and url handling at the same time and this made things messy. I personally believe that you should think about them as two different things.</p><p><strong>However</strong>, you must understand what Router and RouteDelegate are, so if you don’t, check my article <a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-101-for-mobile-dev-5094566613f6?source=your_stories_page-------------------------------------">Flutter Navigator 2.0: 101 for mobile dev</a>.</p><p>Now, let’s look at a very clear schema of what is happening:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-oK5ym5esipYewVp.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*0hL2QdNaZxu7ff6I.gif" /></figure><p><strong>Just kidding, here is the real deal:</strong></p><h3>The theory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1pHXwa9xIG4Nt9CX-C5uw.png" /></figure><p>When you <strong>enter a new url</strong>:</p><ul><li>parseInformationRouter is called, which should <em>convert your url into an Navigation state</em> (wee above what this is).</li><li>Then, setNewRoutePath is called, and should <em>convert the navigation state into your app state</em>.</li></ul><p>When your <strong>app state change</strong>:</p><ul><li>Call routerDelegate.notifyListeners() to warn flutter that the url should be synchronized</li><li>currentConfiguration is called which should <em>convert your app state into a navigation state</em>.</li><li>restoreRouteInformation is called which <em>converts your navigation state into a url</em>.</li></ul><p><strong>What is the navigation state?</strong> It is a class which should hold all the information about the navigation. Why does this exist instead of just having the url as a navigation state? I don’t know, maybe because parsing the url separately (ie in RouteInformationParser is safer). Don’t bother yourself with that, just accept it.</p><p><strong>What is RouteInformationParser?</strong> If you already understand routing, the routerDelegate should sound familiar, however the RouteInformationParser should not. It is just a class which we will implement and override the methods parseRouteInformation and restoreRouteInformation .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*1nID1KfZHEp-0dk2vO2Oww.gif" /></figure><h3>Our example app</h3><p>You can find the code at the end of this article</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*wviez69nfHGPhSYkHZbQ7g.gif" /></figure><p>This is the basic counter app and the url is equal to 10*count .</p><p>Has we saw, we will need to create a RouteInformationParser and a RouterDelegate. To use the, as when routing, we will need to pass them to a Router widget. We also need a class to hold our navigation state.</p><h4><strong>Navigation State</strong></h4><p>Here we just need to keep track of the counter so our class is simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ce994ec5715b1b8ce94bbc5a3a5e8f5/href">https://medium.com/media/7ce994ec5715b1b8ce94bbc5a3a5e8f5/href</a></iframe><h4>The RouteInformationParser</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/008d1cb5604383c8b40aca89a9ddf5a5/href">https://medium.com/media/008d1cb5604383c8b40aca89a9ddf5a5/href</a></iframe><p><strong>parseRouteInformation:</strong></p><p>Called when the url is updated. Its job is to convert the url (contained in routeInformation.location) into the navigation state. Here the url is /counter to we remove the first character and parse the rest. Also note that if the url is not valid, navigationState.value is null.</p><p><strong>restoreRouteInformation:</strong></p><p>This is the inverse function of parseRouteInformation, it takes a NavigationState and convert it into a url. This is called after routerDelegate.currentConfiguration which we will see next.</p><h4>The RouterDelegate</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c713f834ee93e16b9e4d1cc28fd7e12/href">https://medium.com/media/7c713f834ee93e16b9e4d1cc28fd7e12/href</a></iframe><p>The build is not really interesting, it is like any RouterDelegate. Just don’t forget that even if we don’t use routing, having a navigator is interesting because if you don’t have any in you app it can break things (such as overlays).</p><p>The interesting part are: setNewRoutePath, currentConfigurationand increase:</p><p><strong>setNewRoutePath</strong></p><p>Called right after routeInformationParser.parseRouteInformation. It’s job it to convert the navigation state into your app state. This is where all your logic should take place: verifying that the user can access what he/she is trying to access, redirecting if needed. In our case, we check if navigationState.value is null (remember that this is what happens if the url is not valid). If it’s null, we don’t modify our state but call notifyListener so that our url changes back to a correct one. If it is not null, we compute navigationState.value/10 and take the int part. Then we check if the url is in sync with the new counter, if not we call notifyListener .</p><p><strong>currentConfiguration</strong></p><p>This is called when notifyListener is called. It’s job is to change the app state into the navigation state. When this function ends, routeInformationParser.restoreRouteInformation is called with this new navigation state.</p><h4>The Router</h4><p>We just need to put everything into a router and we are done! However note that you can’t use MaterialApp and a Router which handles the url at the same time for now. This is because MaterialApp belongs to Navigator 1 and Router is navigator 2 so their is a conflict. To prevent this, use MaterialApp.router which create a MaterialApp <em>and</em> a Router. Also remember to not use MaterialApp down your widget tree since the same issue will occur. This forces us to have our router really up the widget tree but with most state management libraries this is not an issue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17bb806c77860656546f048738c98494/href">https://medium.com/media/17bb806c77860656546f048738c98494/href</a></iframe><h3>That’s it</h3><p>Go back to the theoretical schema that I show you, and you will see that you understand everything and that you can generalize this to any app!</p><p>Here is the entire code for those who just want to copy/paste 😉</p><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(UrlHandler());<br>}<br><br>class UrlHandler extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp.router(<br>      routerDelegate: UrlHandlerRouterDelegate(),<br>      routeInformationParser: UrlHandlerInformationParser(),<br>    );<br>  }<br>}<br><br>class NavigationState {<br>  final int value;<br>  NavigationState(this.value);<br>}<br><br>final GlobalKey&lt;NavigatorState&gt; _urlHandlerRouterDelegateNavigatorKey =<br>    GlobalKey&lt;NavigatorState&gt;();<br>class UrlHandlerRouterDelegate extends RouterDelegate&lt;NavigationState&gt;<br>    with ChangeNotifier, PopNavigatorRouterDelegateMixin {<br>  int count = 0;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Navigator(<br>      pages: [<br>        MaterialPage(child: MyHomePage(count: count, increase: increase)),<br>      ],<br>      onPopPage: (_, __) {<br>        // We don&#39;t handle routing logic here, so we just return false<br>        return false;<br>      },<br>    );<br>  }<br><br>  @override<br>  GlobalKey&lt;NavigatorState&gt; get navigatorKey =&gt; _urlHandlerRouterDelegateNavigatorKey;<br><br>  // Navigation state to app state<br>  @override<br>  Future&lt;void&gt; setNewRoutePath(NavigationState navigationState) {<br>    // If a value which is not a number has been entered,<br>    // navigationState.value is null so we just notifyListeners<br>    // without changing the app state to change the value of the url<br>    // to its previous value<br>    if (navigationState.value == null) {<br>      notifyListeners();<br>      return null;<br>    }<br><br>    // Get the new count, which is navigationState.value//10<br>    count = (navigationState.value / 10).floor();<br><br>    // If the navigationState.value was not a multiple of 10<br>    // the url is not equal to count*10, therefore the url isn&#39;t right<br>    // In that case, we notifyListener in order to get the valid NavigationState<br>    // from the new app state<br>    if (count * 10 != navigationState.value) notifyListeners();<br>    return null;<br>  }<br><br>  // App state to Navigation state, triggered by notifyListeners()<br>  @override<br>  NavigationState get currentConfiguration =&gt; NavigationState(count*10);<br><br>  void increase() {<br>    count++;<br>    notifyListeners();<br>  }<br>}<br><br>class UrlHandlerInformationParser extends RouteInformationParser&lt;NavigationState&gt; {<br>  // Url to navigation state<br>  @override<br>  Future&lt;NavigationState&gt; parseRouteInformation(RouteInformation routeInformation) async {<br>    return NavigationState(int.<em>tryParse</em>(routeInformation.location.substring(1)));<br>  }<br><br>  // Navigation state to url<br>  @override<br>  RouteInformation restoreRouteInformation(NavigationState navigationState) {<br>    return RouteInformation(location: &#39;/${navigationState.value}&#39;);<br>  }<br>}<br><br>class MyHomePage extends StatefulWidget {<br>  MyHomePage({Key key, this.count, this.increase}) : super(key: key);<br>  final int count;<br>  final VoidCallback increase;<br><br>  @override<br>  _MyHomePageState createState() =&gt; _MyHomePageState();<br>}<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Counter App&#39;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            Text(<br>              &#39;You have pushed the button this many times:&#39;,<br>            ),<br>            Text(<br>              &#39;${widget.count}&#39;,<br>              style: Theme.<em>of</em>(context).textTheme.headline4,<br>            ),<br>          ],<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () {<br>          widget.increase();<br>        },<br>        tooltip: &#39;Counter&#39;,<br>        child: Icon(Icons.<em>add</em>),<br>      ),<br>    );<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffbbb9311219" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Navigator 2.0 for mobile dev: Bloc state management integration]]></title>
            <link>https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-bloc-state-management-integration-3a180b4d25b3?source=rss-940c22f73489------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a180b4d25b3</guid>
            <category><![CDATA[flutter-navigator]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-routing]]></category>
            <dc:creator><![CDATA[Lulupointu]]></dc:creator>
            <pubDate>Thu, 24 Dec 2020 11:04:04 GMT</pubDate>
            <atom:updated>2021-01-22T17:26:35.947Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article is part of a series aiming at making you a master of Navigator 2.0 while showing you that it is not as hard as people think. The other articles of this series are:</em></p><ul><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-101-for-mobile-dev-5094566613f6"><em>Flutter Navigator 2.0: 101 for mobile dev</em></a><em>: Were to start if you have no idea what navigator 2.0 is.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-nested-navigators-basics-2dab6c55010e"><em>Flutter Navigator 2.0 for mobile dev: Nested navigators basics</em></a><em>: How to nest the navigators, and the fix needed to avoid that they ruin your animations</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-transitions-1967b79aaa37"><em>Flutter Navigator 2.0 for mobile dev: Transitions</em></a><em>: How to implement Hero or Page route transitions with navigator 2.0</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-web-dev-url-handling-ffbbb9311219"><em>Flutter Navigator 2.0 for web dev: Url handling</em></a><em>: The basics of URL handling.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-web-url-handling-made-simple-with-simple-url-handler-702ffbaa7a0b"><em>Flutter web: URL handling made simple with simple_url_handler</em></a><em>: How to use the simple_url_handler package to easily manage the url in flutter web.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-web-a-complete-example-using-simple-url-handler-517c2ced805a"><em>Flutter web: A complete example using simple_url_handler</em></a><em>: A complete example, using everything seen above, to build the routing and url handling of a more complete app.</em></li></ul><blockquote>State management is always a concern when building a medium to large size application. In Flutter, the bloc library is really popular. And today, we will see how to use bloc with navigator 2.0.</blockquote><p>Note that this article <strong>is not</strong>:</p><ul><li>A bloc tutorial: find one on their website</li><li>A navigator 2.0 tutorial: for this read my article “<a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-101-for-mobile-dev-5094566613f6">Flutter Navigator 2.0: 101 for mobile dev</a>”</li></ul><p>This article <strong>is</strong>: how to merge the two together</p><h3>What are we going to build?</h3><p>The entire code can be found at the end of this article</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*A2ZojRPaxqTeSgyJzd4G2g.gif" /></figure><p>We will use a bloc to represent the authenticate state of the user (authenticated or not). And we will use the Navigator to move between the Connection screen and the Home screen.</p><h3>How to integrate the two?</h3><p>There are two key elements here:</p><ul><li>Ignore the notifyListeners method of the RouterDelegate</li><li>Use a BlocBuilder to rebuilt the Navigator when needed</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a88a2f13a64627301f7718ec37b52bd/href">https://medium.com/media/8a88a2f13a64627301f7718ec37b52bd/href</a></iframe><p>And just like that you have a declarative navigation based on your bloc state.</p><p>Use BlocProvider.of&lt;AuthenticationBloc&gt;(context).add(UserLoginEvent()) when you need to login and that’s it!</p><h3>Full code</h3><p>Not prettified for easy copy/paste:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br>void main() =&gt; runApp(MyApp());<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider&lt;AuthenticationBloc&gt;(<br>      create: (_) =&gt; AuthenticationBloc(),<br>      child: MaterialApp(<br>        home: Router(<br>          routerDelegate: MyRouterDelegate(),<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>class MyRouterDelegate extends RouterDelegate<br>    with ChangeNotifier, PopNavigatorRouterDelegateMixin {<br>  bool showOtherPage = false;<br>  final GlobalKey&lt;NavigatorState&gt; navigatorKey;<br><br>  MyRouterDelegate() : navigatorKey = GlobalKey&lt;NavigatorState&gt;();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocBuilder&lt;AuthenticationBloc, AuthenticationState&gt;(<br>      builder: (context, authenticationState) {<br>        return Navigator(<br>          key: navigatorKey,<br>          pages: [<br>            MaterialPage(<br>              key: ValueKey(&#39;MyConnectionPage&#39;),<br>              child: MyConnexionWidget(),<br>            ),<br>            if (authenticationState is AuthenticatedState)<br>              MaterialPage(<br>                key: ValueKey(&#39;MyHomePage&#39;),<br>                child: MyHomeWidget(),<br>              ),<br>          ],<br>          onPopPage: (route, result) {<br>            if (!route.didPop(result)) return false;<br><br>            BlocProvider.<em>of</em>&lt;AuthenticationBloc&gt;(context).add(UserLogoutEvent());<br>            return true;<br>          },<br>        );<br>      },<br>    );<br>  }<br><br>  // We don&#39;t use named navigation so we don&#39;t use this<br>  @override<br>  Future&lt;void&gt; setNewRoutePath(configuration) async =&gt; null;<br>}<br><br>class MyConnexionWidget extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Navigator 2.0 101 - Connexion screen&#39;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            FlatButton(<br>              child: Container(<br>                padding: EdgeInsets.all(8.0),<br>                color: Colors.<em>greenAccent</em>,<br>                child: Text(&#39;Click me to connect.&#39;),<br>              ),<br>              onPressed: () =&gt;<br>                  BlocProvider.<em>of</em>&lt;AuthenticationBloc&gt;(context).add(UserLoginEvent()),<br>            )<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>class MyHomeWidget extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Navigator 2.0 101 - Home screen&#39;),<br>      ),<br>      body: Center(<br>        child: Text(&#39;You are connected!&#39;),<br>      ),<br>    );<br>  }<br>}<br><br>class AuthenticationBloc extends Bloc&lt;AuthenticationEvent, AuthenticationState&gt; {<br>  AuthenticationBloc() : super(UnauthenticatedState());<br><br>  @override<br>  Stream&lt;AuthenticationState&gt; mapEventToState(AuthenticationEvent event) async* {<br>    switch (event.runtimeType) {<br>      case UserLoginEvent:<br>        yield AuthenticatedState();<br>        break;<br>      case UserLogoutEvent:<br>        yield UnauthenticatedState();<br>        break;<br>    }<br>  }<br>}<br><br>// Authentication events<br>abstract class AuthenticationEvent {}<br><br>class UserLogoutEvent extends AuthenticationEvent {}<br><br>class UserLoginEvent extends AuthenticationEvent {}<br><br>// Authentication states<br>abstract class AuthenticationState {}<br><br>class UnauthenticatedState extends AuthenticationState {}<br><br>class AuthenticatedState extends AuthenticationState {}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a180b4d25b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Navigator 2.0 for mobile dev: Transitions]]></title>
            <link>https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-transitions-1967b79aaa37?source=rss-940c22f73489------2</link>
            <guid isPermaLink="false">https://medium.com/p/1967b79aaa37</guid>
            <category><![CDATA[flutter-routing]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-navigator]]></category>
            <dc:creator><![CDATA[Lulupointu]]></dc:creator>
            <pubDate>Tue, 22 Dec 2020 23:24:40 GMT</pubDate>
            <atom:updated>2021-01-22T17:25:54.364Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article is part of a series aiming at making you a master of Navigator 2.0 while showing you that it is not as hard as people think. The other articles of this series are:</em></p><ul><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-101-for-mobile-dev-5094566613f6"><em>Flutter Navigator 2.0: 101 for mobile dev</em></a><em>: Were to start if you have no idea what navigator 2.0 is.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-nested-navigators-basics-2dab6c55010e"><em>Flutter Navigator 2.0 for mobile dev: Nested navigators basics</em></a><em>: How to nest the navigators, and the fix needed to avoid that they ruin your animations</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-bloc-state-management-integration-3a180b4d25b3"><em>Flutter Navigator 2.0 for mobile dev: Bloc state management integration</em></a><em>: How to use navigator 2.0 and the bloc library</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-web-dev-url-handling-ffbbb9311219"><em>Flutter Navigator 2.0 for web dev: Url handling</em></a><em>: The basics of URL handling.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-web-url-handling-made-simple-with-simple-url-handler-702ffbaa7a0b"><em>Flutter web: URL handling made simple with simple_url_handler</em></a><em>: How to use the simple_url_handler package to easily manage the url in flutter web.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-web-a-complete-example-using-simple-url-handler-517c2ced805a"><em>Flutter web: A complete example using simple_url_handler</em></a><em>: A complete example, using everything seen above, to build the routing and url handling of a more complete app.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*6bnpw4fHOTI2dbu-.gif" /></figure><h3>What are we going to build?</h3><p>The entire code can be found at the end of this article</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*reXDrDA8sbhEoc-buwQmlA.gif" /></figure><p>Note that this article is not about the basics of Navigator 2.0. If you don’t know how to use them, I would advise to look at my article <a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-101-for-mobile-dev-5094566613f6?source=your_stories_page-------------------------------------">Flutter Navigator 2.0: 101 for mobile dev</a>.</p><p>Also note that my implementation does not take into account the URL for the web so this would need extra work to implement.</p><h3>How to transition between routes?</h3><p>Transition in flutter are done in two ways:</p><ol><li>Hero animations <em>(our red square)</em></li><li>PageRouteBuilder transitions <em>(our centered text)</em></li></ol><h3>1. Hero animations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*H2xGO2gp_sx8jIlyH1O0Uw.gif" /></figure><p>To use hero animation, use the Hero widget having the same tag attribute to encapsulate the widget that is common to your two screen and which you want to animate when transitioning.</p><p><strong>Important:</strong> Their is a known issue where an hero animation won’t by fired. An easy (but needed) fix for this is to pass a HeroController to your Navigator observers attribute:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e87641bacc101f43d70423a6730dd84/href">https://medium.com/media/7e87641bacc101f43d70423a6730dd84/href</a></iframe><p>When this is setup you can use your hero like you would normally do.</p><p>In the profile part we have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0995914ad4f78e9da5b8ba13d0104a7e/href">https://medium.com/media/0995914ad4f78e9da5b8ba13d0104a7e/href</a></iframe><p>And in the settings:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a79a2bae26789fd835bc817c2eebe79d/href">https://medium.com/media/a79a2bae26789fd835bc817c2eebe79d/href</a></iframe><p>When navigating between the two, we can see the square smoothly going from left to right and vise versa !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*H2xGO2gp_sx8jIlyH1O0Uw.gif" /></figure><h3>2. PageRouteBuilder transitions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*qgfs2JC12mQxWl85-z5zNQ.gif" /></figure><p>Those transitions take advantage of the page object that all Navigator’s pages attribute takes. Indeed, if you create a custom class which extends Pages , you can create any transition behavior you want.</p><p>The setting widget is wrap in the default MaterialPage which makes the settings appear from the bottom:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56cedef3237ea651505dbacb82db9259/href">https://medium.com/media/56cedef3237ea651505dbacb82db9259/href</a></iframe><p>But as we said, we can create our own custom Page which will enable us to customize our transition. Here we create a fade transition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2f3394f4cd99c31ba89dea0139f7a10/href">https://medium.com/media/f2f3394f4cd99c31ba89dea0139f7a10/href</a></iframe><p>This is only one example of PageRouteBuilder animation but many can be made, you can find some online in some really good articles like <a href="https://medium.com/flutterdevs/page-transitions-in-flutter-5236a8afae92">Page transitions in Flutter</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*qgfs2JC12mQxWl85-z5zNQ.gif" /></figure><p><strong>Note</strong> that for nested navigator, this gets broken. To fix this you should use a global variable to store you nested navigator key:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e719bf35ca77f01f2b449576bbf45678/href">https://medium.com/media/e719bf35ca77f01f2b449576bbf45678/href</a></iframe><h3>Full code</h3><p>Not prettified for easy copy/paste:</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>main() {<br>  runApp(MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: Router(<br>        routerDelegate: MyRouterDelegate(),<br>      ),<br>    );<br>  }<br>}<br><br>class MyRouterDelegate extends RouterDelegate<br>    with ChangeNotifier, PopNavigatorRouterDelegateMixin {<br>  int selectedIndex = 0;<br>  final GlobalKey&lt;NavigatorState&gt; navigatorKey;<br><br>  MyRouterDelegate() : navigatorKey = GlobalKey&lt;NavigatorState&gt;();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        centerTitle: true,<br>        title: Text(<br>          &#39;Navigator 2.0 - Animations&#39;,<br>        ),<br>      ),<br>      bottomNavigationBar: BottomNavigationBar(<br>        currentIndex: selectedIndex,<br>        items: [<br>          BottomNavigationBarItem(icon: Icon(Icons.<em>person_outline</em>), label: &#39;Profile&#39;),<br>          BottomNavigationBarItem(icon: Icon(Icons.<em>settings_outlined</em>), label: &#39;Settings&#39;),<br>        ],<br>        onTap: onNewIndexSelected,<br>      ),<br>      body: Navigator(<br>        key: navigatorKey,<br>        observers: [HeroController()], // Important to ensure that hero animations are displayed<br>        pages: [<br>          if (selectedIndex == 0)<br>            MyPage(<br>              key: ValueKey(&#39;ProfilePage&#39;),<br>              child: ProfileWidget(<br>                onPressed: () {},<br>              ),<br>            ),<br>          if (selectedIndex == 1)<br>            MaterialPage(<br>              key: ValueKey(&#39;NestedNavigatorPage&#39;),<br>              child: SettingWidget(),<br>            ),<br>        ],<br>        onPopPage: (route, result) {<br>          print(&#39;onPopPage NestedRouterDelegate&#39;);<br>          return false;<br>        },<br>      ),<br>    );<br>  }<br><br>  // We don&#39;t use named navigation so we don&#39;t use this<br>  @override<br>  Future&lt;void&gt; setNewRoutePath(configuration) async =&gt; null;<br><br>  void onNewIndexSelected(int value) {<br>    selectedIndex = value;<br>    notifyListeners();<br>  }<br>}<br><br>class ProfileWidget extends StatelessWidget {<br>  final VoidCallback onPressed;<br><br>  ProfileWidget({@required this.onPressed}) : super();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Stack(<br>      children: [<br>        Positioned(<br>          left: 0,<br>          child: Hero(<br>            tag: &#39;redSquare&#39;,<br>            child: Container(<br>              height: 50,<br>              width: 50,<br>              color: Colors.<em>redAccent</em>,<br>            ),<br>          ),<br>        ),<br>        Center(<br>          child: Container(<br>            padding: EdgeInsets.all(50.0),<br>            color: Colors.<em>amberAccent</em>,<br>            child: Text(&#39;Your profile&#39;),<br>          ),<br>        ),<br>      ],<br>    );<br>  }<br>}<br><br>class SettingWidget extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Stack(<br>      children: [<br>        Positioned(<br>          right: 0,<br>          child: Hero(<br>            tag: &#39;redSquare&#39;,<br>            child: Container(<br>              height: 50,<br>              width: 50,<br>              color: Colors.<em>redAccent</em>,<br>            ),<br>          ),<br>        ),<br>        Center(<br>          child: Container(<br>            padding: EdgeInsets.all(50.0),<br>            color: Colors.<em>greenAccent</em>,<br>            child: Text(<br>              &#39;Your settings&#39;,<br>            ),<br>          ),<br>        ),<br>      ],<br>    );<br>  }<br>}<br><br>class MyPage extends Page {<br>  final Widget child;<br><br>  MyPage({@required this.child, LocalKey key}) : super(key: key);<br><br>  @override<br>  Route createRoute(BuildContext context) {<br>    return PageRouteBuilder(<br>      settings: this,<br>      pageBuilder: (BuildContext context, Animation&lt;double&gt; animation,<br>          Animation&lt;double&gt; secondaryAnimation) {<br>        return FadeTransition(<br>          opacity: animation,<br>          child: child,<br>        );<br>      },<br>    );<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1967b79aaa37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Navigator 2.0 for mobile dev: Nested navigators basics]]></title>
            <link>https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-nested-navigators-basics-2dab6c55010e?source=rss-940c22f73489------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dab6c55010e</guid>
            <category><![CDATA[flutter-navigator]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-routing]]></category>
            <category><![CDATA[flutter-mobile-app]]></category>
            <dc:creator><![CDATA[Lulupointu]]></dc:creator>
            <pubDate>Sun, 20 Dec 2020 13:54:12 GMT</pubDate>
            <atom:updated>2021-02-12T14:11:45.274Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article is part of a series aiming at making you a master of Navigator 2.0 while showing you that it is not as hard as people think. The other articles of this series are:</em></p><ul><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-101-for-mobile-dev-5094566613f6"><em>Flutter Navigator 2.0: 101 for mobile dev</em></a><em>: Were to start if you have no idea what navigator 2.0 is.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-transitions-1967b79aaa37"><em>Flutter Navigator 2.0 for mobile dev: Transitions</em></a><em>: How to implement Hero or Page route transitions with navigator 2.0</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-bloc-state-management-integration-3a180b4d25b3"><em>Flutter Navigator 2.0 for mobile dev: Bloc state management integration</em></a><em>: How to use navigator 2.0 and the bloc library</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-web-dev-url-handling-ffbbb9311219"><em>Flutter Navigator 2.0 for web dev: Url handling</em></a><em>: The basics of URL handling.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-web-url-handling-made-simple-with-simple-url-handler-702ffbaa7a0b"><em>Flutter web: URL handling made simple with simple_url_handler</em></a><em>: How to use the simple_url_handler package to easily manage the url in flutter web.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-web-a-complete-example-using-simple-url-handler-517c2ced805a"><em>Flutter web: A complete example using simple_url_handler</em></a><em>: A complete example, using everything seen above, to build the routing and url handling of a more complete app.</em></li></ul><p>This article assumes that you know the basics of navigator 2.0, if you don’t, check out my other article: <a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-101-for-mobile-dev-5094566613f6">Navigator 2.0 for mobile dev: 101</a>.</p><p>We are going to built on the basics of navigator and try a feature which was greatly improve in 2.0: nested navigator. Having nested navigator has some major advantages:</p><ul><li>It is easier to handle complex app architecture</li><li>It allows you to only redraw the part of the screen you need. It can for example be used to have the same bottom navigation bar for two screens. Having only one instance that does not rebuild is especially useful when the bottom navigation bar is animated for example.</li></ul><p>And two major question come to mind when handling nested navigators:</p><ul><li>How to handle the android back button</li><li>How to handle a pop event (which can be triggered by the BackButtonof the AppBar for example</li></ul><p>And two fix to put in place to fix animation:</p><ul><li>GlobalKey for the navigators, for page route transition</li><li>HeroController() as navigator observer, for hero animation</li></ul><p><em>Note 1: This article is for mobile dev and try to be as simple as possible so it won’t handle web features such as navigation URL.</em></p><p><em>Note 2: This is a guide of basic nesting guide so we won’t look into features such as BackButtonDispatchers.</em></p><h3>The example app:</h3><p>You can find the code at the end of the article</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*AGTcI4dCo9Oaxk7DyFIqTw.gif" /></figure><h3>Our App layout:</h3><p>The important thing to understand is that nesting navigator is pretty simple, just nest them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*D32lffT8qDP01m2W" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fX9pueKj76wbGWH_51xQfg.png" /></figure><p>As you see, nothing complicated. One navigator handles the outer part while the nested one handles the part inside the scaffold.</p><p>What this article is really about is the complications which comes from having nested navigators. And there are two:</p><ol><li>Handling a pop event</li><li>Handling the android back Button</li></ol><h3>Handling a pop event:</h3><p>This can be caused by the <strong>AppBar BackButton</strong>, since it calls Navigator.maybePop(context)by default.</p><p>This event is handled by the Naviatorvia the <strong>onPopPage</strong> method. The important thing to understand is that this event is <strong>local</strong>. This means that it will only call the navigator which we call it on.</p><p>You should be on the page and watch your console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/0*lw6c7cvd5a7eeRRg.png" /></figure><p>The two different behaviors are :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c1be42c668e62780202c19aff63e919/href">https://medium.com/media/0c1be42c668e62780202c19aff63e919/href</a></iframe><p>Clicking the custom <strong>red BackButton</strong> calls the <strong>NestedRouterDelegate Navigator onPopPage </strong>since it is the one in the context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b38edcca97a689a9dbfa77901c4b716f/href">https://medium.com/media/b38edcca97a689a9dbfa77901c4b716f/href</a></iframe><p>Clicking the <strong>scaffold BackButton</strong> calls the <strong>Authentication </strong>RouterDelegate<strong> Navigator</strong> <strong>onPopPage </strong>since it is the one in the context of the scaffold.</p><p><em>If you don’t understand the code in this method checkout my article </em><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-101-for-mobile-dev-5094566613f6"><em>Navigator 2.0 for mobile dev: 101</em></a></p><p>Note that even if we returned false in the custom red BackButton onPopPage (meaning that we don’t handle the pop event), the event does not propagate to the other navigator. This action is <strong>local</strong>.</p><p>If you are not in the right context and you want to call the onPop method of a given navigator you should get the right navigator key and then call navigatorKey.currentState.pop(). But note that this should not be the way to go since it is an imperative way of doing things and Navigator 2.0 is all about being declarative.</p><h3>Handling the android back button:</h3><p>This event is handled completely differently and is <strong>global</strong>.</p><p>With each Router you can get the event, the way it works is:</p><ol><li>The root Router creates a RootBackButtonDispatcher</li><li>Any nested Rooter who want to get the event create a ChildBackButtonDispatcher which should call takePriority() . This ChildBackButtonDispatcher should take Router.of(context).backButtonDispatcher as the parent argument.</li></ol><p>Then when an event if fired:</p><ol><li>The popRoute method of the RouteDelegate associated with the most nested ChildBackButtonDispatcher which called takePriority() is called</li><li>If this method return true, end. Else call the popRoute method of the RouteDelegate of the parent argument of the ChildBackButtonDispatcher.</li><li>Repeat 2 until true or at the RouteDelegate corresponding to the RootBackButtonDispatcher.</li></ol><p><strong>Important note</strong>: If even the popRoutemethod of the RouteDelegate corresponding to the RootBackButtonDispatcher does not return true, then the event is handle by the system and <strong>closes the app causing it to crash. </strong>To avoid this behavior, I would advice you to use the <a href="https://pub.dev/packages/move_to_background">move_to_background</a> library and call MoveToBackground.moveTaskToBack() before returning true. This will put the application in the background gracefully.</p><h3>Fixing animation problems:</h3><p>Nested navigator break 2 things: <strong>PageRouteTransitions</strong> and <strong>HeroAnimations</strong>. Hopefully this will be fix in the future, however in the meantime, luckily for us, there is a fix for each of those.</p><h4>PageRouteTransitions</h4><p>The issue here occures when the key given to the Navigator is rebuilt. The fix here is to create them as global variable (or equivalent, depending on your state managment choice):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b217788460e3a4bed08cd1efe7956acf/href">https://medium.com/media/b217788460e3a4bed08cd1efe7956acf/href</a></iframe><h4>HeroAnimations</h4><p>The issue here has to do with hero controller, though I can’t really explain what is going on, the fix is to give a new HeroController to the Navigator observers attribute:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/159dc0579254e91afd9bedf658a13414/href">https://medium.com/media/159dc0579254e91afd9bedf658a13414/href</a></iframe><h4>TL;DR:</h4><p>Nesting navigator is pretty simple, just nest them. The only issue come from:</p><ol><li><em>Handle a pop event</em> called by the BackButton of the AppBar</li><li><em>Handle Android back button</em></li></ol><p><em>Handle a pop event</em> a local event and calls the onPopPage method of the closest navigator in the context.</p><p><em>Handle Android back button</em> is a global event, handled with a stack. The element are inserted in the stack by passing BackButtonDispacher to your routers <em>[</em><em>RootBackButtonDispacher for the root navigator, </em><em>ChildBackButtonDispacherwhich call </em>takePriority <em>for the others]</em>. At each event, the popRoute method of the RouteDelegate associated lest element in the stack is called. If this method returns true we stop, else we call the previous element in the stack and so on.</p><p>Animations get broken, here are the two fix:</p><ul><li>Fix PageRouteTransition: use a global variable to store your nested navigator key</li><li>Fix HeroAnimation: use observers=[HeroController()] is you nested navigator</li></ul><h4>The example code</h4><p>Not prettified, just for easy copy paste:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:move_to_background/move_to_background.dart&#39;;<br><br>void main() {<br>  runApp(MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: Router(<br>        routerDelegate: AuthenticationRouterDelegate(),<br>        backButtonDispatcher: RootBackButtonDispatcher(),<br>      ),<br>    );<br>  }<br>}<br><br>class AuthenticationRouterDelegate extends RouterDelegate with ChangeNotifier {<br>  bool isAuthenticated = false;<br>  final GlobalKey&lt;NavigatorState&gt; navigatorKey;<br><br>  AuthenticationRouterDelegate() : navigatorKey = GlobalKey&lt;NavigatorState&gt;();<br><br>  @override<br>  Future&lt;bool&gt; popRoute() async {<br>    print(&#39;popRoute AuthenticationRouterDelegate&#39;);<br>    MoveToBackground.<em>moveTaskToBack</em>();<br>    return true;<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Navigator(<br>      key: navigatorKey,<br>      observers: [HeroController()],<br>      pages: [<br>        MaterialPage(<br>          key: ValueKey(&#39;MyHomePage&#39;),<br>          child: MyAuthenticationWidget(<br>            onPressed: () {<br>              isAuthenticated = true;<br>              notifyListeners();<br>            },<br>          ),<br>        ),<br>        if (isAuthenticated)<br>          MaterialPage(<br>            key: ValueKey(&#39;NestedNavigatorPage&#39;),<br>            child: NestedRouterWidget(),<br>          ),<br>      ],<br>      onPopPage: (route, result) {<br>        print(&#39;onPopPage AuthenticationRouterDelegate&#39;);<br>        if (!route.didPop(result)) return false;<br><br>        isAuthenticated = false;<br>        notifyListeners();<br>        return true;<br>      },<br>    );<br>  }<br><br>  // We don&#39;t use named navigation so we don&#39;t use this<br>  @override<br>  Future&lt;void&gt; setNewRoutePath(configuration) async =&gt; null;<br>}<br><br>class MyAuthenticationWidget extends StatelessWidget {<br>  final VoidCallback onPressed;<br><br>  MyAuthenticationWidget({@required this.onPressed}) : super();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;You are connected&#39;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            TextButton(<br>              child: Container(<br>                padding: EdgeInsets.all(8.0),<br>                color: Colors.<em>greenAccent</em>,<br>                child: Text(&#39;Click me to connect.&#39;),<br>              ),<br>              onPressed: onPressed,<br>            )<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}<br><br>class NestedRouterWidget extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    final childBackButtonDispatcher =<br>        ChildBackButtonDispatcher(Router.<em>of</em>(context).backButtonDispatcher);<br>    childBackButtonDispatcher.takePriority();<br>    return Router(<br>      routerDelegate: NestedRouterDelegate(),<br>      backButtonDispatcher: childBackButtonDispatcher,<br>    );<br>  }<br>}<br><br>final GlobalKey&lt;NavigatorState&gt; _nestedNavigatorKey = GlobalKey&lt;NavigatorState&gt;();<br><br>class NestedRouterDelegate extends RouterDelegate with ChangeNotifier {<br>  int selectedIndex = 0;<br><br>  @override<br>  Future&lt;bool&gt; popRoute() async {<br>    print(&#39;popRoute NestedRouterDelegate&#39;);<br>    return false;<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;You are connected&#39;),<br>      ),<br>      bottomNavigationBar: BottomNavigationBar(<br>        currentIndex: selectedIndex,<br>        items: [<br>          BottomNavigationBarItem(icon: Icon(Icons.<em>person_outline</em>), label: &#39;Profile&#39;),<br>          BottomNavigationBarItem(icon: Icon(Icons.<em>settings_outlined</em>), label: &#39;Settings&#39;),<br>        ],<br>        onTap: onNewIndexSelected,<br>      ),<br>      body: Navigator(<br>        key: _nestedNavigatorKey,<br>        observers: [HeroController()],<br>        pages: [<br>          if (selectedIndex == 0)<br>            MaterialPage(<br>              key: ValueKey(&#39;ProfilePage&#39;),<br>              child: ProfileWidget(<br>                onPressed: () {},<br>              ),<br>            ),<br>          if (selectedIndex == 1)<br>            MaterialPage(<br>              key: ValueKey(&#39;NestedNavigatorPage&#39;),<br>              child: SettingWidget(),<br>            ),<br>        ],<br>        onPopPage: (route, result) {<br>          print(&#39;onPopPage NestedRouterDelegate&#39;);<br>          return false;<br>        },<br>      ),<br>    );<br>  }<br><br>  // We don&#39;t use named navigation so we don&#39;t use this<br>  @override<br>  Future&lt;void&gt; setNewRoutePath(configuration) async =&gt; null;<br><br>  void onNewIndexSelected(int value) {<br>    selectedIndex = value;<br>    notifyListeners();<br>  }<br>}<br><br>class ProfileWidget extends StatelessWidget {<br>  final VoidCallback onPressed;<br><br>  ProfileWidget({@required this.onPressed}) : super();<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Center(<br>      child: Text(&#39;Your profile&#39;),<br>    );<br>  }<br>}<br><br>class SettingWidget extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Center(<br>      child: Column(<br>        mainAxisSize: MainAxisSize.min,<br>        children: [<br>          Text(&#39;Your settings&#39;),<br>          TextButton(<br>            child: Container(color: Colors.<em>redAccent</em>, child: Icon(Icons.<em>arrow_back_ios</em>)),<br>            onPressed: () {<br>              return Navigator.<em>pop</em>(context);<br>            },<br>          )<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dab6c55010e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Navigator 2.0: 101 for mobile dev]]></title>
            <link>https://lucasdelsol01.medium.com/flutter-navigator-2-0-101-for-mobile-dev-5094566613f6?source=rss-940c22f73489------2</link>
            <guid isPermaLink="false">https://medium.com/p/5094566613f6</guid>
            <category><![CDATA[flutter-routing]]></category>
            <category><![CDATA[flutter-navigator]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Lulupointu]]></dc:creator>
            <pubDate>Sat, 19 Dec 2020 13:36:28 GMT</pubDate>
            <atom:updated>2021-12-17T09:55:14.545Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter Navigator 2.0 for mobile dev: 101</h3><p><em>This article is part of a series aiming at making you a master of Navigator 2.0 while showing you that it is not as hard as people think. The other articles of this series are:</em></p><ul><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-nested-navigators-basics-2dab6c55010e"><em>Flutter Navigator 2.0 for mobile dev: Nested navigators basics</em></a><em>: How to nest the navigators, and the fix needed to avoid that they ruin your animations</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-transitions-1967b79aaa37"><em>Flutter Navigator 2.0 for mobile dev: Transitions</em></a><em>: How to implement Hero or Page route transitions with navigator 2.0</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-mobile-dev-bloc-state-management-integration-3a180b4d25b3"><em>Flutter Navigator 2.0 for mobile dev: Bloc state management integration</em></a><em>: How to use navigator 2.0 and the bloc library</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-navigator-2-0-for-web-dev-url-handling-ffbbb9311219"><em>Flutter Navigator 2.0 for web dev: Url handling</em></a><em>: The basics of URL handling.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-web-url-handling-made-simple-with-simple-url-handler-702ffbaa7a0b"><em>Flutter web: URL handling made simple with simple_url_handler</em></a><em>: How to use the simple_url_handler package to easily manage the url in flutter web.</em></li><li><a href="https://lucasdelsol01.medium.com/flutter-web-a-complete-example-using-simple-url-handler-517c2ced805a"><em>Flutter web: A complete example using simple_url_handler</em></a><em>: A complete example, using everything seen above, to build the routing and url handling of a more complete app.</em></li></ul><blockquote>Flutter recently release Navigator 2.0, its new navigation system. While this is suppose to give developers more flexibility and ease (with a declarative approach), the new system faced many criticism. In my opinion, this is only due to one thing: presentation. Indeed, the main resource when I am writing this is this medium article: <a href="https://medium.com/flutter/learning-flutters-new-navigation-and-routing-system-7c9068155ade">https://medium.com/flutter/learning-flutters-new-navigation-and-routing-system-7c9068155ade</a>. But it should be called “an advanced courses on how to implement navigator 2.0 on the web” not “Learning Flutter’s new navigation and routing system”. I would argue that navigator 2.0 is not only more powerful but also as simple as navigator 1.0, and this is what I will demonstrate in this article.</blockquote><p>Note that this article is meant to introduce the very basics and won’t support web functionality such as URL handling.</p><h4>Final result:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*Glun7N3WCsa3nhe2cw0olQ.gif" /></figure><h4>App architecture:</h4><ul><li>MyApp: contains the MaterialApp and the Router</li><li>MyRouterDelegate: our main focus here. This is the widget handling the navigation</li><li>MyHomeWidget: the first page with the button</li><li>MyOtherWidget: the page which appears on top of MyHomePage</li></ul><h4>Classic Flutter:</h4><p>Let’s get the usual part out of the way. Here are MyHomeWidget , MyOtherWidget and MyApp :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16180b9e4ecd6cee34a5e8f44696b697/href">https://medium.com/media/16180b9e4ecd6cee34a5e8f44696b697/href</a></iframe><p>This should all look familiar if you already coded a flutter app.</p><p>The only new part is in MyApp where you put the Router widget. Instead of passing the usual child, you pass a routerDelegate. Nothing scary here just a different name 🙂</p><h4>Now off to the interesting part : the RouterDelegate</h4><p>Here is the code, see the explanation below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acad808f1fd6a80546579224135de2da/href">https://medium.com/media/acad808f1fd6a80546579224135de2da/href</a></iframe><p>Regarding the mixins:</p><ul><li>ChangeNotifier is the class which enable us to call notifyListeners() whenever the route changes. This is the equivalent of calling setState in a way.</li><li>PopNavigatorRouterDelegateMixin is just a class which implements the method popRoute for you to handle backbutton press. <a href="https://github.com/flutter/flutter/blob/b793285329fa4289a3076882308ef3781bd2de18/packages/flutter/lib/src/widgets/router.dart#L1259-L1272">Look at the source code</a> you will see it&#39;s just that.</li></ul><p>3 elements remain to be implemented:</p><ul><li>setNewRoutePath which we don&#39;t use since we are not on the web</li><li>navigatorKey which is a key to refer to our navigator. It is used by the PopNavigatorRouterDelegateMixin and you can use it to navigate in an imperative way (though you should never need)</li><li>build which should look familiar. The only special thing about this one is that you should return a Navigator and not any widget in this implementation.</li></ul><h4><strong>The widget you are here for:</strong> Navigator</h4><ul><li>You should pass the navigatorKey to its key parameter</li><li>pages is the stack of pages describing our navigation stack in a declarative way. Note that we don&#39;t use directly the widget but rather MaterialPage. At this point you should not worry about it but know that MaterialPage describes for example the transition between different route. Also note that the key parameter should be used in order to properly animate between the pages.</li><li>onPopPage is where you must change your internal state to reflect the pop (if route.didPop(result)returned true). In our case we set showOtherPage to false</li></ul><p>And that all! As you see nothing really complicated, we could sum everything up like so:</p><h3>TL;DR:</h3><p><em>Here is how to use Navigator 2.0 for mobile dev.</em></p><p>Return a Router with the routerDelegate argument.</p><p>Create a RouterDelegate class which is basically a widget which:</p><ul><li>Should return a Navigator in its build method</li><li>Creates a navigator key to pass to the navigator</li><li>calls should notifyListener instead of setState to rebuild</li></ul><p>The navigator:</p><ul><li>defines pages which are your app widgets wrapped in MaterialPage stacked in a declarative way</li><li>defines onPopPage (which must return route.didPop(result)) to handle any pop event.</li></ul><p>Here is the entire code for those who just want to copy/paste 😉</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fde649f42b1bc6b96dd89af517915e8/href">https://medium.com/media/3fde649f42b1bc6b96dd89af517915e8/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5094566613f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>