GetX: Route Managment

padymies
3 min readNov 9, 2021

Guide to managing the routes of a Flutter application helped by the Getx package.

In a previous article, we looked at the advantages of the GetX package and focused on State managment. If you haven’t seen it yet, I recommend you take a look at it, as this is one of the features that brings the most benefits to your code.

Today we will talk about route management. With GetX we can manage the routes of the application, navigate and even pass parameters between screens, all in a simple way and with few lines of code.

Let’s get started!

We start by installing the package in our dependencies

dependencies:
get: ^4.3.8

The first thing we need to know is that, in order for Get to manage the routes of an app, we have to replace the MaterialApp with a GetMaterialApp.

Don’t panic. Behind the scenes GetMaterialApp returns a MeterialApp so really we still have the same thing, but with added functionality.

This Widget has a large number of properties, although we will focus on the ones we need to manage the routes:

InitialRoute: we pass the initial route that will be loaded when the app starts up.

GetPages: we must pass the routes of the application. I recommend having the routes in a separate file. In this example we have it in routes.dart, which contains a function that returns an array with the different routes and their screens.

GetPage also receives quite a few properties, although the only required ones are the name of the path (name) and the screen that will be loaded (page).

As you can see in the code above, we can also configure transitions and even middelwares to be launched when the route is invoked.

Navigating between screens

Once our application is configured to handle the routes through Get, we are ready to navigate between the different screens in a simple way through the methods offered by this package:

Get.to(OneScreen())Get.toNamed(‘/route-name’)Get.off(() => NextScreen())Get.offAll(()=> NextScreen())Get.back()

With Get.to() or Get.toNamed() we can return to the previous screen by pressing the device’s back button. Get.off() and Get.offAll(), on the other hand, removes screens from the stack so that you cannot go back to them. Get.back() scrolls back through the stack of screens.

Passing arguments

All these methods allow us to pass arguments to routes in the following way:

Get.to(OneScreen(), arguments: {‘someArgument: ‘someInfo’})

To get those arguments on the screen is as simple as this:

Get.arguments['someArgument'] // someInfo

This would be a good start for route management via Get. There are many more configuration options that we haven’t seen here, but you will find that when you start playing with the Get ecosystem.
I encourage you to apply Get’s state and route management in a project, you’ll see how much benefit it brings to your code.

I hope you found this article useful. 😊

--

--

padymies

Software Developer. “Learn to share, share to learn”