GetX Navigation Basics
As I told in the post about Showing Snackbars using GetX, GetX is an awesome all-in-one package. Another great feature in GetX is easy navigation without a lot of boilerplate code.
The most useful feature of GetX navigation is not the decreased number of Lines of Code, but The ability to use these within our Business Logic.
As they don’t need context, we can simply use them inside our Business Logic 😊.
Navigate to New Page
We know, Navigation in Flutter consist of lots of code. For just navigating to another page, we have to write
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => SecondPage(),
),
);
but in GetX, all we wanna do is
Get.to(
() => SecondPage(),
);
Three lines of code instead of Five! Isn’t it awesome?
Go back / close current route
For closing current route in Normal way, we would do,
Navigator.pop(context);
in GetX,
Get.back();
Close current route and push a new One instead
In this scenario, the normal way would be to
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
),
);
in getx
Get.off(()=>HomePage());
yes! just one line!
Close several pages and Push new page
To close several pages and push a new page to stack, the normal way would be,
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => HomePage(),
),
(route) => false);
in getx,
Get.offAll(()=>HomePage());
Important ⚠️
Obviously, to all of these to work, we have to change our MaterialApp to a GetMaterialApp like it told in my post about GetX SnackBars
I think this post was useful to you. If it is, please do share this in your circle, so that more people can make use of this 😊. And Follow me on Twitter for getting more posts like these 😉.
Also if you found any mistakes or have any suggestions, don’t hesitate to ping me on my Twitter or to drop a mail at [email protected].
If you fancy reading more posts related to getx, go over here.