Flutter getx routes management example

Hi Guys, Welcome to Proto Coders Point, In this Flutter tutorial we will discuss Flutter Getx Route Management, getx routing Made easy with this awesome library.

What is Flutter GetX?

The GetX library in flutter is a very extra lightweight plugin & a powerful package that will help flutter developers to build apps much faster.

Using GetX we can easily switch between screens, show snack bar, show dialog, and bottom sheet that too without passing any context.

Then, it combines high-performance state management, intelligent dependency injection & route management that too quickly.

learn more:  Introduction to getx library

Learn more in detail about this library from the official site

https://pub.dev/packages/get

Video Tutorial

 

Installation of GetX plugin

Create a new Flutter Project and under your project, you will see pubspec.yaml file open it: add this package under the dependencies section

dependencies:
  get: ^3.13.2   #check official site of latest version

import it and use it wherever required

import 'package:get/get.dart';

Ok, So now we are done with the basic requirement,

In this tutorial, we will check only GetX Route Management, So let’s begin

Flutter Getx Routes Management

If you want to create a snack bar, dialogs, bottom sheet, and a complete routers of your flutter then, GETX is excellent to make use of:

Note: To use getx  you need to wrap the root of your flutter project with GetMaterialApp instead of using simply MaterialApp

snippet code

GetMaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      home: HomePage(),
      theme: ThemeData(

        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
    );

As you can see in the above snippet code I have just wrapped the root node with GetMaterialApp so that I can use getx properties anywhere in the application.

Properties of Getx Routes

Navigate to a new screen

Get.to(nextScreen());

To go to the next Screen & no option  to go back to the previous screen ( you can use this in SplashScreen, Registration Screen or Login Screen )

Get.off(nextScreen());

Then, to go to the next screen but you want to forget all the previous routes that you traveled then use this:

Get.offAll(NextScreen());

Using Flutter Routes name

Snippet Code

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,

      // starting point from where app should begin
      initialRoute: '/',

      //when initial Route is given no need to add home widget for initial start point of app
      //full app route structure

      routes: {
        '/':(context)=> MyHomePage(),
        '/login':(context)=>LoginPage(),
        '/reg':(context)=>Registration(),
        '/dashboard':(context)=>Dashboard()
      },

      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
    );
  }
}

As you can see in the above code,
I have created some routes to other pages in your app,
So now will be check Getx properties that can help you in Navigation using Routes Names.

Navigation to named routes

Get.toNamed('/login');   // this will take you to login page

Navigation to named Routes but forget/removing all previously traveled routes

Get.offAllNamed('/dashboard');

Goes to the next page, and then removes the previous one.

Get.offAndToNamed('/dashboard');

Demo Project- just to Demonstrate Route Management using GetX

This is the project structure
Project Structure getx flutterNote: This is just a dummy project with a simple login registration screen(without any actual functionality) just to show Route management in flutter using GetX.

Here are the Codes

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_getx_routes/Dashboard.dart';
import 'package:flutter_getx_routes/LoginPage.dart';
import 'package:flutter_getx_routes/MyHomePage.dart';
import 'package:flutter_getx_routes/Registration.dart';
import 'package:get/get.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      // starting point from where app should begin
      initialRoute: '/',
      //when initial Route is given no need to add home widget for initial start point of app
      //full app route structure

      routes: {
        '/':(context)=> MyHomePage(),
        '/login':(context)=>LoginPage(),
        '/reg':(context)=>Registration(),
        '/dashboard':(context)=>Dashboard()
      },

      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
    );
  }
}



MyHomePage.dart

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FlatButton(onPressed: (){
                  Get.toNamed('/login');
            }, child: Text("GO TO LOGIN PAGE ",style: TextStyle(color: Colors.white),),color: Colors.blue,)
          ],
        ),
      ),
    );
  }
}

 


Registration.dart

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

class Registration extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("Registration page",style: TextStyle(fontSize: 25),),
              //// textField only for Simple UI, there is not event happening in it
              Padding(
                padding: const EdgeInsets.only(left: 25,right: 25),
                child: TextField(
                    decoration:  InputDecoration(
                      hintText: "User Name",
                    )
                ),
              ),Padding(
                padding: const EdgeInsets.only(left: 25,right: 25),
                child: TextField(
                    decoration:  InputDecoration(
                      hintText: "Password",
                    )
                ),
              ),
              SizedBox(height: 20,),
              FlatButton(onPressed: () {

                // after registration successful remove all the previous screen visited and goto dashboard page
                Get.offAllNamed('/dashboard');

              } ,
             child: Text("Register",style: TextStyle(color: Colors.white),),color: Colors.blue,),
              SizedBox(height: 10,),

              //// Go to Login page from registration if already registered  using getx toNamed properties

              GestureDetector(onTap: ()=> Get.offAllNamed('/login'),child: Text("Already Done ? Login Now ")),
            ],
          ),
        ),
      ),
    );
  }
}

LoginPage.dart 

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

class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("Login page",style: TextStyle(fontSize: 25),),
              //// textField only for Simple UI, there is not event happening in it
              Padding(
                padding: const EdgeInsets.only(left: 25,right: 25),
                child: TextField(
                    decoration:  InputDecoration(
                      hintText: "User Name",
                    )
                ),
              ),Padding(
                padding: const EdgeInsets.only(left: 25,right: 25),
                child: TextField(
                    decoration:  InputDecoration(
                      hintText: "Password",
                    )
                ),
              ),
              SizedBox(height: 20,),
              FlatButton(onPressed: () {

                // after Login successful remove all the previous screen visited and goto dashboard page
                Get.offAllNamed('/dashboard');

              } , child: Text("Login",style: TextStyle(color: Colors.white),),color: Colors.blue,),
              SizedBox(height: 10,),

              //// Go to Registration page is new user using getx toNamed properties
              GestureDetector(onTap: ()=> Get.toNamed('/reg'),child: Text("New User? Register Now")),
            ],
          ),
        ),
      ),
    );
  }
}

Dashboard.dart

import 'package:flutter/material.dart';

class Dashboard extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: Text("Dashboard page"),
        ),
      ),
    );
  }
}

Output

flutter getx route management example output

Recommended Articles on Flutter Getx

Introduction to getX Flutter example

Flutter State management using GetX

Comments are closed.