How do I Implement Navigation with GetX Flutter

Last updated Oct 21, 2021


In this flutter example we will cover how to implement Navigation with Getx instead of basic Navigator component. In the previous example we covered how to use GetX controller to Manage the State of the widget.

 

Navigation in GetX

To implement Navigation between different screens with GetX we need to change our MaterialApp widget from previous example to GetMaterialApp widget

 

Let's get started

Step 1: Create Flutter application

Step 2: Add Getx dependency in publspec.yaml file

dependencies:
  flutter:
    sdk: flutter
  get: ^4.3.8

 

Step 4: Let's create a two Screens with Stateless Widgets.

FirstPage

import 'package:flutter/material.dart';
import 'package:flutter_getx/views/secondpage.dart';
import 'package:get/get.dart';

class FirstPage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {

    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Scaffold(
        appBar: AppBar(),
        body: Container(
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text("GetX Navigation",style: TextStyle(fontSize: 20),),
                SizedBox(height: 20,),
                MaterialButton(onPressed: (){
                  
                },color: Colors.red,
                  textColor: Colors.white,
                  child: Text("Second Screen",style: TextStyle(fontSize: 20),),)
              ],
            ),
          ),
        ),
      ),
    );
  }

}

 

Second Page:

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

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('About GetX'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text(
                'Flutter GetX Framework to Handle State,navigation,Dependency...',style: TextStyle(fontSize: 20),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

 

Now we are ready with two screens. To navigate from First Screen to Second Screen we will add the Get.to() method inside onPressed() method of Materail Button widget.

onPressed: (){
  Get.to(SecondPage());
}

 

When we run the above example we can see the Navigation from First Screen to Second Screen on tap on Second Screen Material Button.

 

On From Screens two if we press device back button we will navigate back to First Screen.

 

Replace Screen with GetX Navigation

In some times we may require to replace the Current screen with Next Screen while Navigation. To replace Screens we will use Get.off() GetX method

 

In the above example replace Get.to(SecondPage()) with Get.off(SecondPage()) and let's run the application.

 

When you navigate from First Page to Second Page, from the second page if we press the back button app will terminate instead of navigate to First Page, because Get.off() replace the current screen with next screen and remove the first screen from the stack.

 

How to Goback Previous Screen with GetX?

So we have replaced First Screen with Second Screen by using Get.off(), if we want to go back to First screen we will use  Get.back() method

 

MaterialButton(onPressed: (){
  Get.back();
}

 

Update Second screen code like below


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

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('About GetX'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text(
                'Flutter GetX Framework to Handle State,navigation,Dependency...',style: TextStyle(fontSize: 20),
              ),
            ),
            MaterialButton(onPressed: (){
              Get.back();
            },color: Colors.red,
              textColor: Colors.white,
              child: Text("First Screen",style: TextStyle(fontSize: 20),),)
          ],
        ),
      ),
    );
  }
}

 

How do i Pass argument Using GetX?

To pass Arguments from one screen to other Screen we will use GetX argument attribute while Navigate to the screens

Get.to(SecondPage(),arguments: [200]

 

On the Next Screen we will read the Argument by below code

(Get.arguments!=null)?Text(" ${Get.arguments[0]}"):Text(""),

 

How do i get the Result data Using GetX?

To Get the result from the other screen we will pass the Result data inside Get.back with result attribute

 

Get.back(result: "From Second Page result 200");

 

 

Navigate with Name Routes with GetX

We can Navigate screen using Named routes. To create Routes we will use GetMaterialApp widget and creates the routes by using below way

GetMaterialApp(
  getPages: [
    GetPage(name: '/third', page: () => ThirdPage()),

  ],

)

 

Here we create Named Route for the ThirdPage

We will call this ThirdPage like below

onPressed: () {
  Get.toNamed("/third");
},

 

Getx Navigation Flutter

 

GetX Named Routes Navigation

 

 

 

Complete code for Getx Navigation

homepage

import 'package:flutter/material.dart';
import 'package:flutter_getx/views/firstpage.dart';
import 'package:flutter_getx/views/secondpage.dart';
import 'package:flutter_getx/views/thirdpage.dart';
import 'package:get/get.dart';

class Home extends StatelessWidget {
  goToNext() {
    Get.to(FirstPage());
  }





  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      getPages: [
        GetPage(name: '/third', page: () => ThirdPage()),

      ],
      home: Scaffold(
        appBar: AppBar(
          title: Text("Get Package | Home"),
          centerTitle: true,
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              MaterialButton(color: Colors.red,
                textColor: Colors.white,
                child: Text("Go To FirstPage"),
                onPressed: () => goToNext(),
              ),
              SizedBox(
                height: 40,
              ),
              MaterialButton(color: Colors.red,
                textColor: Colors.white,
                child: Text("Go To Second Page with Arguments"),
                onPressed: () => Get.to(SecondPage(),arguments: [200]),
              ),
              SizedBox(
                height: 40,
              ),
              MaterialButton(
                color: Colors.blue,
                textColor: Colors.white,
                child: Text("Name Route: /third"),
                onPressed: () {
                  Get.toNamed("/third");
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}

 

 

FirstPage

import 'package:flutter/material.dart';
import 'package:flutter_getx/views/secondpage.dart';
import 'package:get/get.dart';

class FirstPage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(title:Text("GetX Navigation Example")),
      body: Container(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text("GetX Navigation",style: TextStyle(fontSize: 20),),
              SizedBox(height: 20,),
              MaterialButton(onPressed: ()async{
                var result=  await Get.to(() => SecondPage(),arguments: [100]);
                print(result);
              },color: Colors.red,
                textColor: Colors.white,
                child: Text("Second Screen",style: TextStyle(fontSize: 20),),)
            ],
          ),
        ),
      ),
    );
  }

}

 

Second Page:


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

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('About GetX'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text(
                'Flutter GetX Framework to Handle State,navigation,Dependency...',style: TextStyle(fontSize: 20),
              ),
            ),
            SizedBox(
              height: 40,
            ),
            (Get.arguments!=null)?Text("Arguments from Home ${Get.arguments[0]}",style: TextStyle(fontSize: 16)):Text(""),
            SizedBox(
              height: 40,
            ),
            MaterialButton(onPressed: (){
              Get.back(result: "From Second Page result 200");
            },color: Colors.red,
              textColor: Colors.white,
              child: Text("First Screen",style: TextStyle(fontSize: 20),),)
          ],
        ),
      ),
    );
  }
}

 

Third Page

import 'package:flutter/material.dart';

class ThirdPage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Third Page by Route Name GetX'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text(
                'Flutter GetX Framework to Handle State,navigation,Dependency...',style: TextStyle(fontSize: 20),
              ),
            ),
            SizedBox(
              height: 40,
            ),

          ],
        ),
      ),
    );
  }

}

 

main.dart

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

 

 

Conclusion: In this Flutter Getx tutorial we covered what is getX navigation, how to Navigate with Getx and GetX Named Routes, pass data between screens using GetX


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

43 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions