[GetX] Route management

2022-01-24 hit count image

Let's see how to manage the Route by GetX in Flutter .

Outline

In this blog post, I will introduce how to manage the Route by GetX in Flutter. You can see full source code of this blog post on the link below.

Blog series

This blog post is made in the series about how to use GetX in Flutter. If you want to see the other features of the GetX, please check out the following blog posts.

GetX installation

To check how to use GetX in Flutter, execute the command below to create a new Flutter project.

flutter create route_management

And then, execute the command below to install the GetX package.

flutter pub add get

Now, let’s see how to manage the route by GetX.

Route management

To use GetX features in Flutter, you need to use GetMaterialApp instead of MaterialApp. To check this, open the lib/main.dart file and modify it like the below.

...
@override
Widget build(BuildContext context) {
  return GetMaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    home: const MyHomePage(),
  );
}
...

Next, modify the MyHomePage widget that is shown first time like the below.

...
class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TextButton(
          child: const Text('Next Screen'),
          onPressed: () => Get.to(const Second()),
        ),
      ),
    );
  }
}
...

The MyHomePage is a simple widget that has the TextButton in the center of the screen, and when you press the button, you can move to the Second screen.

To the Second widget, you can use the Get.to of the GetX like the below.

Get.to(const Second())

Next, to create the Second widget, create the lib/second.dart file and modify it like the below.

import 'package:flutter/material.dart';
import 'package:get/get.dart';

class Second extends StatelessWidget {
  const Second({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TextButton(
          onPressed: () => Get.back(),
          child: const Text('Go back'),
        ),
      ),
    );
  }
}

The Second widget is also a simple widget that has the TextButton in the center of the screen, and when you press the button, you can go back to the previous screen.

To go back the previous screen, you can use the Get.back of the GetX like the below.

Get.back()

In GetX, you can use the Get.to with the widget class directly to make the screen transition simply.

Named route

Howeber, if you use the widget class directly like the above, you can implement the screen transition, but it’s difficult to manage the route. So, in GetX, normally we use the Named route to manage the route.

To check the Named route, modify lib/main.dart file like the below.

...
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/',
      getPages: [
        GetPage(name: '/', page: () => const MyHomePage()),
        GetPage(name: '/second', page: () => const Second()),
      ],
    );
  }
}
...

Unlike before, we configure the screen name and widget(page) by the GetPage class. And, the first screen of the app is configured to the initialRoute option.

We can use the Flutter for the Web, so normally, the URL is used for the name.

Next, let’s see how to move the screen by the Named route. Modify the MyHomePage widget that has a button to move the screen like the below.

...
class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TextButton(
          child: const Text('Next Screen'),
          onPressed: () => Get.toNamed('/second'),
        ),
      ),
    );
  }
}
...

Now, to move the screen, we can use Get.toNamed with registered name.

Pass arguments

You can pass the arguments like the below when you move the screen.

Get.toNamed("/first", arguments: "Hello");

To access the parameters, you can use the code below.

Get.arguments

Also, you can use the URL parameter like the below.

getPages: [
  GetPage(name:"/", page: () => Home()),
  GetPage(name:"/first/:id", page: () => First()),
]
...
Get.toNamed("/first/1?name=hello");
...
Get.parameters["id"]
Get.parameters["name"]

To check this, modify the lib/main.dart like the below.

...
class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TextButton(
          child: const Text('Next Screen'),
          onPressed: () => Get.toNamed(
            '/second',
            arguments: {
              "greeting": "Hello",
              "name": "World",
            },
          ),
        ),
      ),
    );
  }
}
...

And then, modify the lib/second.dart file like the below.

...
class Second extends StatelessWidget {
  const Second({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('${Get.arguments['greeting']}, ${Get.arguments['name']}'),
            TextButton(
              onPressed: () => Get.back(),
              child: const Text('Go back'),
            ),
          ],
        ),
      ),
    );
  }
}
...

When you execute the code, you can see Hello, World in the screen. The arguments is the dynamic type, so you can pass any type of data.

How to move the screen

When you move the screen, you can stack the new screen on top of the previous screen. However, sometimes you want to add a new screen with removing the previous screen, or move to the previous screen and then add a new screen.

In GetX, you can use the features like the below to implement them.

Get.until

  • Remove screens until satisfying the condition.
  • It’s the same with Navigation.popUntil().
  • You can use it like Get.until((route) => Get.currentRoute == '/home').

Get.off

  • Remove the current screen and add a new screen.
  • It’s the same with Navigation.pushReplacement().
  • You can use it like Get.off(Second()).

Get.offNamed

  • By the Named route, remove the current screen and add a new screen.
  • It’s the same with Navigation.pushReplacementNamed().
  • You can use it like Get.offNamed('/second').

Get.offAndToNamed

  • By the Named route, add a new screen and then, remove the previous screen.
  • It’s the same with Navigation.popAndPushNamed().
  • You can use it like Get.offAndToNamed('/second').

Get.offUntil

  • Remove screens until satisfying the condition, and then, add a new screen.
  • It’s the same with Navigation.pushAndRemoveUntil().
  • You can use it like Get.offUntil(page, (route) => (route as GetPageRoute).routeName == '/home').

Get.offNamedUntil

  • By the Named route, remove screens until satisfying the condition, and then, add a new screen.
  • It’s the same with Navigation.pushNamedAndRemoveUntil().
  • You can use it like Get.offNamedUntil(page, ModalRoute.withName('/home')).

Get.removeRoute

  • Remove the screen that is satisfied the condition.
  • It’s the same with Navigation.removeRoute().
  • You can use it like Get.removeRoute(ModalRoute.withName('/home')).

Get.offAll

  • Remove all screens and then, add a new screen.
  • It’s the same with Navigation.pushNamedAndRemoveUntil().
  • You can use it like Get.offAll(Second()).

Get.offAllNamed

  • By the Named route, remove all screens and then, add a new screen.
  • It’s the same with Navigation.pushNamedAndRemoveUntil().
  • You can use it like Get.offAllNamed('/second').

Animation

In GetX, you can use the Transition in GetPage to make the animation when the screen is changed.

getPages: [
  GetPage(name:"/", page: () => Home()),
  GetPage(name:"/second", page: () => Second(), transition: Transition.leftToRight),
]

You can use the animations like the below.

  • Transition.fade,
  • Transition.fadeIn,
  • Transition.rightToLeft,
  • Transition.leftToRight,
  • Transition.upToDown,
  • Transition.downToUp,
  • Transition.rightToLeftWithFade,
  • Transition.leftToRightWithFade,
  • Transition.zoom,
  • Transition.topLevel,
  • Transition.noTransition,
  • Transition.cupertino,
  • Transition.cupertinoDialog,
  • Transition.size,
  • Transition.native

Also, you can control the details of the animation like the below.

GetPage(
  name: "/second",
  page: () => SecondScreen(),
  transition: Transition.rightToLeft,
  transitionDuration: const Duration(milliseconds: 400),
  curve: Curves.fastOutSlowIn,
)

Swipe back

In GetX, you can use the popGesture to implement the Swipe back(Gesture back) feature.

GetPage(
  name: "/second",
  page: () => SecondScreen(),
  popGesture: true,
)

If the popGesture is true, you can use the swipe back feature, and if it is false, you can’t use the swipe back feature.

Check the previous screen

You can use the Get.previousRoute to check the previous screen in GetX.

Get.previousRoute

Completed

Done! we’ve seen how to manage the route by GetX in Flutter. Also, we’ve seen various ways about how to move the screen, and how to pass the arugments.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts