Easy navigation in Flutter with go_router

Thiago Evoá
3 min readOct 21, 2021

--

Hello dev, I don’t know if you have been followed the “news” about navigation navigation 2.0 in Flutter, but in the community I saw a lot of people complaining about the difficult to implement that, so I decided to try and see what happens, and yeah it’s not straight forward to me at first time.

These days I saw a twitter from Chris Sells talking about this package called go_router, and I decided to read about. At first It seems to be easy to implement, and after using It my thought was… Why is It not implemented by default in the SDK? So here I’ll show you a very simple example just to make you curious as well.

First thing you need to do is creating a new Flutter project as usual, and after that add to the pubspec.yaml file the go_router package and thats it for now.

pubspec.yaml

Now let’s define the routes, and for that let’s create a file called routes.dart and declare some constants and the routes itself using the GoRouter class like the image below.

routes.dart

The thing here that you need to take care is provide a list of routes and in this case I put the second_page.dart as a sub route of the home_page.dart because I wanted to have the back button on the AppBar, and a errorPageBuilder to render the error page when something goes wrong. Oh, one tip for you… take a look at the go_router documentation in order to understand more.

All right, so now you need to make a fell changes on the MaterialApp widget, first change it to MaterialApp.router, and then add the routeInformationParser and the routerDelegate provided by the router object you created before.

main.dart

Now it’s time to create the first screen which I called home_page.dart, and in this example I just created a simple list and I added in each ListTile a onTap action using the go_router sintax to call the second_page.dart.

This navigation package give us a short syntax while using the context, and here you just need to pass the route path you want to call and in this case I also passed an extra parameter with the item clicked on the list in order to show on the second_page.dart.

home_page.dart

So after creating the second_page.dart, I decided to just have the clicked item appearing in the center of the screen.

second_page.dart

And the last page is the error_page.dart which is going to be the one that will appear when something goes wrong in the route.

error_page.dart

As the result you can see the web app navigating through the pages, and notice that if the user try to access a page that does not exist, the go_router package will handle that and show the error_page.dart with an exception.

result

That is it folks, if you got interested about using this package just take a look at the documentation to see the other possibilities of usage and try to see if it fits in your project.

--

--