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!
Note: You can find the whole source code provided in this tutorial here
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.
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
_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
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: