go_router is a very popular routing solution, that makes Flutters Navigator 2.0 easy again. In this article, you will learn how to use it and will see, how easy it is to use. Let’s get started!
Happy reading!
Note: You can find the whole source code provided in this tutorial here
Installation
The first thing we have to do after creating our app is to add go_router. To do so, we will use the command flutter pub add go_router
. You should be familiar with those commands, otherwise, I recommend you to look up the basics of Flutter again.
Getting started
The first thing we have to create is a variable of Type GoRouter
. We will store all routes there:
Now, instead of writing a plain MaterialApp
, we will use MaterialApp.router
. There we can customize settings for routes and still use the features of MaterialApp
. Inside the MaterialApp.router
, we set routeInformationProvider
to _router.routeInformationProvider
, routeInformationParser
to _router.routeInformationParser
and routerDelegate
to _router.routerDelegate
. As you can see, GoRouter already gives us so many predefined variables and functions that are so easy to use.
But we have forgotten something. What if we navigate to a path that doesn’t exist? Simple. In your _router
variable add errorBuilder
before routes
and define an error screen:
Navigate with GoRouter
Navigating with GoRouter is very easy. There are two ways of navigation with GoRouter. One is very similar to “normal” navigation with any package and the other one is a more concise way using Dart extension methods:
Further reading & Conclusion
In this article, you have learned the basics of the Navigator 2.0 solution “go_router”. You have seen how easy it is to use.
You can unfold the whole power of go_router if you use packages like Freezed, Isar, or Riverpod. If you want to learn these additions, I have entire tutorials about them. Check them out here.
In the following few articles, I will introduce more somewhat complicated packages and explain them. If you don’t want to miss this, I recommend you to follow me. I tried my best to write the easiest tutorial which everyone understands. If you appreciate this work, I would be very grateful if you could support this quality content and give me some claps!
Thanks for reading, have a nice day!