Using GetX (Get) for Navigation and Routing in Flutter

Last updated on May 18, 2021 A Goodman Loading... Post a comment

Introduction

Flutter already provides built-in navigator APIs that can help us navigate between screens (routes) and show dialogs, snack bars, bottom sheets without installing a third-party library. They are good and easy to use. However, if you want to write less code and speed up your development process, you can use GetX (also called Get). Furthermore, you can use routes, snack bars, dialogs, bottom sheets without context.

A quick example

The two code snippets below do the same thing: Navigating to a route named SomeScreen.

Using Flutter’s Navigator:

Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SomeScreen()),
);

Using GetX:

Get.to(SomeScreen());

Obviously, the 2nd way is much shorter and doesn’t need to worry about context.

Note: GetX comes with a lot of features but each of these features is in separate containers and is only started after use. If you only use Route Management, only Route Management will be compiled.

In this article, we’ll go over a few examples of navigation and routing with GetX. If you want to learn how to manage states with GetX, see this article.

Example: Navigating Between Screens

App Preview

This example shows you how to navigate by using route names and not using route names. Our app has 5 screens:

  • HomePage: Contains buttons that lead to other screens
  • PageOne: Displays a number passed in from the Home page via arguments. There is a back button to go back.
  • PageTwo: There is no back button in the app bar.
  • PageThree: Displays a number passed in from the Home page via arguments. There is a back button to go back.
  • PageFour: Displays a number passed from the Home page via the dynamic route name.

Here’s how it works:

The Code

1. Install GetX by executing this command:

flutter pub add get

2. Import the library into your Dart code:

import 'package:get/get.dart';

In lib/main.dart, replace “MaterialApp” with “GetMaterialApp”.

3. The complete code:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      theme: ThemeData(primarySwatch: Colors.deepOrange),
      home: HomePage(),
      getPages: [
        GetPage(name: '/page-three', page: () => PageThree()),
        GetPage(
            name: '/page-four/:data', page: () => PageFour()) // Dynamic route
      ],
    );
  }
}

// Home Screen
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Navigate ising screen classes'),
            ElevatedButton(
                onPressed: () => Get.to(PageOne(), arguments: {
                      'id': Random().nextInt(1000).toString()
                    }), // Passing data by using "arguments"
                child: Text('Go to page One')),
            ElevatedButton(
                onPressed: () => Get.off(PageTwo()),
                child: Text('Go to page Two (Can not go back)')),
            Divider(),
            Text('Navigate Using named routes'),
            OutlinedButton(
                onPressed: () => Get.toNamed('/page-three',
                    arguments: {'id': Random().nextInt(10000).toString()}),
                child: Text('Go to page Three')),
            OutlinedButton(
                onPressed: () => Get.toNamed(
                      '/page-four/${Random().nextInt(10000)}',
                    ),
                child: Text('Go to page Four'))
          ],
        ),
      ),
    );
  }
}

// Page One
class PageOne extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Page One'),
      ),
      body: Center(
        child: Text(
          Get.arguments['id'] ?? 'Page One',
          style: TextStyle(fontSize: 40),
        ),
      ),
    );
  }
}

// Page Two
class PageTwo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Page Two'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () => Get.off(HomePage()),
          child: Text('Go Home'),
        ),
      ),
    );
  }
}

// Page Three
class PageThree extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Page Three'),
      ),
      body: Center(
        child: Text(
          Get.arguments['id'] ?? 'Page Three',
          style: TextStyle(fontSize: 40),
        ),
      ),
    );
  }
}

// Page Four
class PageFour extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Page Four'),
      ),
      body: Center(
        child: Text(
          Get.parameters['data'] ?? 'Page Four',
          style: TextStyle(fontSize: 40),
        ),
      ),
    );
  }
}

Example: Dialog, Snack Bar, and Bottom Sheet

This example shows you how to display a dialog, a snack bar, and a bottom sheet by using GetX. We don’t need “context” at all.

Preview

The Code

Delete everything in your main.dart then add the following:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      theme: ThemeData(primarySwatch: Colors.green),
      home: HomePage(),
    );
  }
}

// Home Screen
class HomePage extends StatelessWidget {
  // This function is triggered when the "Show Dialog" button pressed
  void _showDialog() async {
    await Get.dialog(AlertDialog(
      title: Text('Dialog Title'),
      content: Text('This is the dialog content'),
      actions: [
        TextButton(
            onPressed: () => Get.back(), // Close the dialog
            child: Text('Close'))
      ],
    ));

    // Code that runs after the dialog disappears
    print('Dialog closed!');
  }

  // This function is triggered when the "Show SnackBar" button pressed
  void _showSnackBar() {
    Get.snackbar('SnackBar Title', 'This is a beautiful snack bar',
        duration: Duration(seconds: 3),
        snackPosition: SnackPosition.BOTTOM,
        snackStyle: SnackStyle.FLOATING);
  }

// This function is triggered when the "Show BottomSheet" button pressed
  void _showBottomSheet() async {
    await Get.bottomSheet(Container(
      width: double.infinity,
      height: 300,
      color: Colors.greenAccent,
      child: Center(
        child: Text('Bottom Sheet Content'),
      ),
    ));

    // The code below will run after the bottom sheet goes away
    print('The Bottom Sheet has gone away!');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ElevatedButton(onPressed: _showDialog, child: Text('Show Dialog')),
            ElevatedButton(
                onPressed: _showSnackBar, child: Text('Show SnackBar')),
            ElevatedButton(
                onPressed: _showBottomSheet, child: Text('Show BottomSheet')),
          ],
        ),
      ),
    );
  }
}

Conclusion

You’ve learned and gone through several examples of navigating with GetX. Continue exploring more about developing apps with Flutter by taking a look at the following articles: Flutter + Firebase Storage: Upload, Retrieve, and Delete filesUsing GetX (Get) for State Management in FlutterFlutter and Firestore Database: CRUD example 2 ways to fetch data from APIs in FlutterMost Popular Packages for State Management in Flutter.

You can also check out our Flutter category page, or Dart category page for the latest tutorials and examples.

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x