Perfect Guide for GetX Routes Management in Flutter
Routing between screens is a crucial aspect of developing apps with Flutter technology. However, managing routes can be complex and challenging at times. That’s why I’m here to provide you with a comprehensive tutorial on how to manage routes in GetX Flutter.
You might be wondering why GetX is the best option for route management in Flutter applications.
GetX significantly simplifies route management by allowing easy navigation between screens, transitions, and passing arguments.
It’s no wonder that the GetX package is the most popular choice among developers, as evidenced by the screenshot from the pub.dev.
In addition to route management, GetX offers a range of other useful services, including state management, dependency management, local storage, GetX Server, and API integration with GetConnect.
For the purpose of this article, we’ll be focusing solely on route management. Keep reading to discover some of the key advantages of using GetX for this aspect of your app development.
GetX Route Management Pros
- You can easily navigate between screens without needing to pass a context.
- Ability to incorporate transition animations between screens.
- Display the snack bar, dialog, and bottom sheet without the need for context.
- Ability to add middleware to protect routes.
- Transferring data between screens using arguments is incredibly simple and straightforward with GetX.
To help you better understand the concept of GetX route management, I will provide a comparison with Flutter route management.
This will allow you to gain a clearer understanding of how GetX differs and what benefits it can offer.
Installation
The initial step is to install the most recent package by executing the following command. Upon running this command, the latest version of the package will be installed in your project.
flutter pub add get
Next, you will need to change your MaterialApp to GetMaterialApp in order to utilize the route management feature.
However, if you plan on using other services such as state management or dependency management, there is no need to switch to GetMaterialApp. Simply continue using MaterialApp.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'routes.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
/// MaterialApp to GetMaterialApp for route management.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: 'GetX Routes Demo by IntendStuff',
initialRoute: Routes.page1,
getPages: pages,
);
}
}
Routes Declaration
At this point, it is recommended to create a separate file named ‘routes.dart’ and add all the screens or pages of your application as routes within this file.
import 'package:get/get.dart';
/// used to declare all the routes in strings so that
/// we can navigate through only the page names
class Routes {
static String page1 = "/page1";
static String page2 = "/page2";
static String page3 = "/page3";
static String page4 = "/page4";
static String page5 = "/page5";
static String page6 = "/page6";
}
/// assign this list variable into your GetMaterialApp as the value of getPages parameter.
/// you can get the reference to the above GetMaterialApp code.
final pages = [
GetPage(
name: Routes.page1,
page: () => const Page1(),
),
GetPage(
name: Routes.page2,
page: () => const Page2(),
),
GetPage(
name: Routes.page3,
page: () => const Page3(),
),
GetPage(
name: Routes.page4,
page: () => const Page4(),
),
GetPage(
name: Routes.page5,
page: () => const Page5(),
),
GetPage(
name: Routes.page6,
page: () => const Page6(),
),
];
Having defined the routes, it’s time to explore some of the best features of GetX for navigating between screens.
1) To navigate between screens without context, the code would look something like this:
Get.to(() => const Page2());
This works in the same way as,
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const Page2(),
),
);
If you wish to navigate between screens using their designated names, as we have defined a class called “Routes”, then you can do so by using the following code:
Get.toNamed(Routes.page2);
This works in the same way as,
Navigator.pushNamed(context, Routes.page2);
As you have observed, GetX routes can be used without context, which is one of the best problem-solving features in GetX. Below, you can find a comparison of all the GetX routes with Flutter routes.
Get.to() | Navigator.push() |
Get.toNamed() | Navigator.pushNamed() |
Get.back() | Navigator.pop(context) |
Get.off() | Navigator.pushReplacement() |
Get.offNamed() | Navigator.popAndPushNamed() |
Get.offUntil() | Navigator.pushAndRemoveUntil() |
Get.offNamedUntil() | Navigator.pushNamedAndRemoveUntil() |
Get.offAndToNamed() | Navigator.popAndPushNamed() |
Get.removeRoute() | Navigator.removeRoutes() |
Get.offAllNamed() | Navigator.pushNamedAndRemoveUntil() |
Get.close() | Navigator.popUntil() |
At the moment, we have completed only the navigation aspect. Therefore, let us now focus on learning how we can effortlessly transmit data between screens without the need to pass values through constructors.
Flutter Related Post,
Arguments: Passing Data Between Screens in GetX Flutter
To send this map to a specific screen through GetX navigation, all I need to do is pass it in the [arguments] parameter.
Map<String, dynamic> response = {
"data": [
{"name": "Parth Darji"},
{"name": "Vedant Darji"},
],
"message": "All data get successfully"
};
Get.to(() => const Page2(), arguments: response);
Once we navigate to the screen, we can retrieve the arguments we passed through the GetX arguments parameter by implementing this code on the screen.
class Page2 extends StatefulWidget {
const Page2({super.key});
@override
State<Page2> createState() => _Page2State();
}
class _Page2State extends State<Page2> {
var arguments = Get.arguments; // -----> this line
@override
Widget build(BuildContext context) {
print(arguments); // ----------------> this line
return const Scaffold(
body: Center(
child: Text("Page 2"),
),
);
}
}
You will get your argument printed in the console.
[GETX] GOING TO ROUTE /Page2
I/flutter ( 4596): {data: [{name: Parth Darji}, {name: Vedant Darji}], message: All data get successfully}
Please note that there is another parameter called \[parameters] that functions similarly to arguments. However, it only supports the Map\<String, String> data type. On the other hand, arguments support dynamic types, which means you can pass arguments of any data type.
Transitions: PageTransitions in GetX Flutter
If you desire a visually appealing transition during navigation, use the following code. Feel free to test and experiment with it.
Get.to(
LoginScreen(),
arguments: response,
// This is how you give transitions.
transition: Transition.leftToRightWithFade,
);
Below is a list of various types of transitions available.
- 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
Additionally, it is possible to set the duration of the transition between navigations.
Get.to(
LoginScreen(),
arguments: response,
// This is how you give transitions.
transition: Transition.leftToRightWithFade,
// This is how you can set the duration for navigating the screen.
duration: const Duration(seconds: 3),
);
Furthermore, there are additional parameters related to navigation that you can explore in the Get function.
- binding
- curve
- fullscreenDialog
- gestureWidth
- id
- opaque
- popGesture
- preventDuplicates
- routeName
Please note that I cannot provide you with the complete documentation for GetX here. However, you can navigate to the GetX library code by pressing the control (on the keyboard) and left-click button. This will allow you to explore all of the features that they have provided.
Middlewares: How To Protect Routes in GetX Flutter
Let’s now understand how to safeguard the routes from unauthorized access. For instance, you may want to restrict access to routes to only those users who are logged in.
This is particularly useful for premium screens in mobile apps and is essential for web applications.
To achieve this, we need to create a middleware file called ‘route_guard.dart’ in your project. You may choose any name for this file, but it should have the suffix ‘_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;
}
}
Next, you need to call this middleware in the GetPage function that we declare in ‘routes.dart’ as follows:
GetPage(
name: _Paths.dashboard,
page: () => DashboardScreen(),
middlewares: [RouteGuard()],
),
You can add multiple middlewares to the List type. When the dashboard route is triggered in the application, the RouteGuard middleware class will be invoked to check for the availability of userToken.
If a token is available, then the user can navigate anywhere in the application except for the login screen.
We can also add a LoginGuard middleware to restrict access to the login screen for logged-in users. This is particularly useful for Flutter Web applications (because of URLs). In mobile applications, it is easy to handle by clearing routes.
Flutter Related Posts,
GetX Bonus Features
In GetX, you can display dialogs, snack bars, and bottom sheets without the need for context.
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
While we have covered the perfect guide for GetX route management, there is still much more to discover within this expansive framework. Due to its size and complexity, it’s impossible to cover everything in one blog post.
For optimal results, it’s recommended to utilize the entire GetX ecosystem. If you found this post helpful, please share it with your fellow Flutter developers, and be sure to follow IntendStuff blogs for more tutorials on Flutter.