Flutter – Navigation without context using GetX package

Navigation is an important part of any front-end framework. Flutter is not an exception, it provides Navigator class with many built-in methods. However, there is a drawback with this Navigator tool: the context. When using those methods, you always have to provide it a context (required parameter). This is not convenient when we want to do the navigation outside the widgets, in that case we have to find a way to pass the context around.

There are various solutions to solve this inconvenience (Ex: using global key) but in this post I only share my favorite approach with GetX package, a multi-purposes package for navigation (route management), state management, dependencies management.

1. Add the package to your project

Open pubspec.yaml file and add the package to your dependencies:

dependencies:
  get: ^3.17.1

Get the package by running this command:

flutter pub get

2. Wrap your app under GetMaterialApp

By default, your Flutter app will be wrapped under MaterialApp (under main.dart or under your custom .dart file). We need to replace your MaterialApp by GetMaterialApp. GetMaterialApp has almost the same properties with MaterialApp, in my case I don’t need to change any other thing.

@override
Widget build(BuildContext context) {
    // Replace MaterialApp by GetMaterialApp
    // return MaterialApp(...);
    return GetMaterialApp(...);
}

3. Start to use Get for your navigation

After above steps, now you’re ready to use Get for your navigation and don’t worry about the context anymore.

// Navigate to new screen
Get.to(NewScreen());

// Go back or close dialog, bottom sheet... 
// Similar to Navigator.pop(context)
Get.back();

// Navigate to new screen and clear current screen 
// (can not go back to current screen)
Get.off(NewScreen());

// Navigate to screen and clear all previous screens in the stack
Get.offAll(NewScreen());

If you want to use GetX for named routes, follow this document session.

4. Custom your navigation

You obviously can add more parameters to to the methods I listed in step 3. Here is the signature of Get.to method (similar signature for other methods in step 3):

Future<T> to<T>(
    Widget page, {
    bool opaque,
    Transition transition,
    Curve curve,
    Duration duration,
    int id,
    bool fullscreenDialog = false,
    dynamic arguments,
    Bindings binding,
    bool preventDuplicates = true,
    bool popGesture,
  }) {...}

To make it more convenient and we can also reuse it (as we will use navigation at many places in the app), I create a global function:

// navigation.dart

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

/// Navigate to target screen (widget).
///
/// [screen] Target screen.
///
/// [transition] Transition effect.
///
/// [clearStack] If provided (= true), go to next screen 
/// and clear all previous screens.
///
/// [offCurrentScreen] If provided (= true), go to next 
/// screen and can not go back to current screen.
///
/// [preventDuplicates] Allow duplicated widget or not, 
/// set to "false" to allow duplication.
///
/// [popGesture] Set to true if you want to pop back to 
/// previous screen using drag from the left edge of the screen.
///
Future navigateTo(Widget screen,
    {Transition transition,
    bool clearStack = false,
    bool offCurrentScreen = false,
    bool preventDuplicates = true,
    Duration duration,
    bool popGesture = false}) async {
  
  // Change to your favorite transition
  final t = transition ?? Transition.rightToLeftWithFade;
  
  // Change the duration if you need
  final d = duration ?? const Duration(milliseconds: 250);
  if (clearStack) {
    return Get.offAll(screen, transition: t, duration: d);
  } else if (offCurrentScreen) {
    return Get.off(screen, transition: t, duration: d);
  } else {
    return Get.to(screen,
        transition: t,
        duration: d,
        preventDuplicates: preventDuplicates,
        popGesture: popGesture);
  }
}

// Use it
navigateTo(NewScreen());

If you are looking for mobile/web Software Engineers to build you next projects, pleaseĀ Contact Nextfunc team here!

Tagged : / / / /
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x