Guide to Routes Management Using GetX in Flutter
Almost every app needs to navigate from one screen to another in flutter technology. But flutter makes route management complex sometimes. So today I am going to give you a tutorial on how to manage routes in GetX Flutter.
You will ask why GetX is best for route management for flutter applications. The GetX makes route management very simple and easy to navigate between screens with transitions and sending the argument on the screen. Hence, GetX package is the most liked package in pub. dev as you can see in the screenshot.
Not only route management, GetX provides other services as well.
Such as
- State Management
- Dependency Management
- Local Storage
- GetX Server
- API Integration with GetConnect
However, we are going to see only route management for now, and below are the advantages of flutter GetX route management.
GetX Route Management Advantages
- Navigate between the screen without context.
- Can give transition animation between the screen.
- Can show snackbar, dialog, and bottomsheet without context.
- You can add middleware easily to protect the routes.
- Transfer the data through [arguments] very easily.
I will give you the GetX route management explanation by comparing it with flutter route management so you can understand it clearly.
Installation
So first of all, you need to install the latest package by running this command. This will install the latest available package in your project.
flutter pub add get
After that, you need to change your MaterialApp to GetMaterialApp. After changing it you can use route management. If you want to use another service such as state management, dependency management, etc. then you don’t need to change to GetMaterialApp, stay with MaterialApp.
/// MaterialApp to GetMaterialApp for route management.
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: Routes.screen1,
getPages: getPages,
);
}
Routes Declaration
Now, let’s add all the screens or pages that you have in your application in a separate file as routes. dart.
/// Routes name to directly navigate the route by its name
class Routes {
static String screen1 = '/screen1;
static String screen2 = '/screen2;
static String screen3 = '/screen3;
static String screen4 = '/screen4;
static String screen5 = '/screen5;
static String screen6 = '/screen6;
}
/// Add this list variable into your GetMaterialApp as the value of getPages parameter.
/// You can get the reference to the above GetMaterialApp code.
final getPages = [
GetPage(
name: Routes.screen1,
page: () => const Screen1(),
),
GetPage(
name: Routes.screen2,
page: () => const Screen2(),
),
GetPage(
name: Routes.screen3,
page: () => const Screen3(),
),
GetPage(
name: Routes.screen4,
page: () => const Screen4(),
),
GetPage(
name: Routes.screen5,
page: () => const Screen5(),
),
GetPage(
name: Routes.screen6,
page: () => const Screen6(),
),
];
GetX Navigation
This is how you can define routes. Now, let’s navigate between the screen with some GetX best features.
1) If you want to navigate between the screen without context then I have to code like this.
Get.to(const Screen2());
This is work same as,
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const Screen2()),
);
2) If you want to navigate between the screen by their names as we defined a class named Routes
Get.toNamed(Routes.screen2);
This works the same as,
Navigator.pushNamed(context, Routes.screen2);
You’ve seen that you can use flutter GetX routes without context and this is the best problem-solving feature in GetX.
Here are all the GetX routes compared with flutter routes.
Get.to() | Navigator.push() |
Get.toNamed() | Navigator.pushNamed() |
Get.back() | Navigator.pop(context) |
Get.off() | Navigator.pushReplacement() |
Get.offNamed() | Navigator.pushReplacementNamed() |
Get.offUntil() | Navigator.pushAndRemoveUntil() |
Get.offNamedUntil() | Navigator.pushNamedAndRemoveUntil() |
Get.offAndToNamed() | Navigator.popAndPushNamed() |
Get.removeRoute() | Navigator.removeRoutes() |
Get.offAllNamed() | Navigator.pushNamedAndRemoveUntil() |
Get.close() | Navigator.popUntil() |
For now, only the navigation part is completed. Now, let’s learn about how we can send data between the screen easily without passing values between constructors.
Arguments – How to Send Data Between Screens in GetX
I want to send this map to the screen that I provide in the GetX navigation. So I need to just pass in the [arguments] parameter.
Map response = {
"data": [
{"name": "Parth Darji"},
{"name": "Darshan Popat"},
{"name": "Jitendra Mistry"}
],
"message": "All data get successfully"
};
Get.to(Screen1(), arguments: response);
After navigating the screen we need to get those arguments that we send in the GetX arguments parameters. So simply do this on your screen.
var data = Get.arguments;
print(data[“message”]);
Note: There is also one parameter called [parameters], it is working the same as arguments. But it is only supporting Map<String, String> type. And arguments support dynamic type, meaning you can send any type of arguments.
Transitions – How to Apply Transitions in GetX
On navigation, if you want to give a beautiful transition then here is the code, you can test it further.
Get.to(
LoginScreen(),
arguments: response,
// This is how you give transitions.
transition: Transition.leftToRightWithFade,
);
There are different types of transitions. You can see the list below.
- Transition.fade
- Transition.fadeIn
- Transition.rightToLeft
- Transition.leftToRight
- Transition.upToDown
- Transition.downToUp
- Transition.rightToLeftWithFade
- Transition.zoom
- Transition.topLevel
- Transition.noTransition
- Transition.cupertino
- Transition.cupertinoDialog
- Transition.size
- Transition.circularReveal
- Transition.native
You can also set the duration between navigation for transition.
transition: Transition.leftToRightWithFade,
// This is how you can set the duration for navigating the screen.
duration: const Duration(seconds: 3),
Also there are other parameters you can explore in the Get. to navigation.
- binding
- curve
- fullscreenDialog
- gestureWidth
- id
- opaque
- popGesture
- preventDuplicates
- routeName
Note: If you want to explore more about GetX, I cannot give you the full documentation here. You can press (the control + mouse left-click) button to navigate to the GetX library code. And you can explore all features that they provided.
Middlewares – How To Protect Routes in GetX
Now, let’s learn how to protect the routes so that unauthorized users cannot access them. For example, you want to create routes that only logged-in users can access. Mostly this can be used in the Premium screen in the mobile apps and for the web, it is very necessary. Then this will help you.
So first, you need to create a middleware file named (route_guard.dart) in your project. You can name any with the suffix of (_guard).
/// User cannot go to the dashboard screen if he doesn’t have a login token.
class RouteGuard extends GetMiddleware {
@override
RouteSettings redirect(String route) {
return userToken == null ? const RouteSettings(name:Routes.login): null;
}
}
Now, call this middleware in GetPage that we declare in routes. dart like this.
GetPage(
name: _Paths.dashboard,
page: () => DashboardScreen(),
middlewares: [RouteGuard()],
),
You can multiple middlewares in its List type. When this dashboard route is triggered in the application the RouteGuard middleware class will be called and it will determine whether userToken is available or not.
If a token is available then the user can navigate anywhere in the application except login because we can also code LoginGuard for logged-in users if the user is already logged then the user cannot navigate to the login screen. This is mostly useful in Flutter Web.
GetX Bonus Features
You can show dialog, snackbars, bottom sheets without context in GetX.
1) Dialog
Get.defaultDialog(
radius: 10.0,
contentPadding: const EdgeInsets.all(20.0),
title: 'title',
middleText: 'content',
textConfirm: 'Okay',
confirm: OutlinedButton.icon(
onPressed: () => Get.back(),
icon: const Icon(
Icons.check,
color: Colors.blue,
),
label: const Text(
'Okay',
style: TextStyle(color: Colors.blue),
),
),
cancel: OutlinedButton.icon(
onPressed: () {},
icon: Icon(Icons.tap_and_play),
label: Text('label'),
),
);
2) Snackbar
Get.snackbar(
'title',
'message',
snackPosition: SnackPosition.BOTTOM,
colorText: Colors.white,
backgroundColor: Colors.black,
borderColor: Colors.white,
);
3) BottomSheet
Get.bottomSheet(
Container(
height: 150,
color: Colors.grey,
child: Center(
child: Text(
'Count has reached ${obxCount.value.toString()}',
style: const TextStyle(fontSize: 28.0, color: Colors.black),
),
),
),
);
Conclusion
That’s all done for flutter GetX route management. GetX routing is a simple and efficient way to handle navigation in Flutter apps. There is more to tell about the GetX framework but it is a very big framework and I think in one blog we cannot add everything.
Managing routes in Flutter can be made simple and easy with the help of GetX. It is an excellent package for route management and simplifies the process of navigating between screens in Flutter apps.
If you use the whole GetX ecosystem then it works best. If you like this post then share it with your flutter developer colleagues and make sure that you follow OneClick blogs to get more tutorials like this on flutter.