Skip to main content

Command Palette

Search for a command to run...

How to navigate without context in Flutter?

In this mini-blog, we will learn how to eliminate context from Navigation in Flutter.

Updated
โ€ข2 min read
How to navigate without context in Flutter?
D

Flutter developer at Securrency |Previously Uni, GoHighLevel | Organizer Flutter Gwalior | Public Speaker ๐ŸŽ™๏ธ | Blogger ๐Ÿ“ | Exploring new Tech

Navigation is an integral part of any App. Flutter makes it really easy to navigate to any screen by using simple navigator functions like Push and Pop.

To push:

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

To Pop:

Navigator.pop(context);

This works great until your app scales and you separate your business logic with the UI logic. And now you have to pass BuildContext from one function to another function. This becomes a big hassle sometimes and there are times when you want to avoid passing on context.

Don't worry NavigatorKey is to the rescue.

1. Create a Navigator Key

static final navigatorKey = GlobalKey<NavigatorState>();

2. Pass the Navigator Key in MaterialApp

    return MaterialApp(
      ...
      navigatorKey: AppRouter.navigatorKey,
    );

3. Push using the Navigator Key

navigatorKey.currentState?.push(
    MaterialPageRoute(builder: (_) => SecondRoute()),
);

That's it with just 3 easy steps you can eliminate context from your Navigation. You can check the full code on Github.


Thank you for reading ๐Ÿ‘‹

I hope you enjoyed this article. If you have any queries or suggestions please let me know in the comments down below.

You can connect with me on Twitter, Github and LinkedIn. You can subscribe to my newsletter at the top of the page to get an email notification for my latest articles.

Happy Coding... See you next time ๐Ÿ‘‹

D

Works like a charm! Thanks for sharing.

1
D

Glad it helped.

D

Very interesting and knowledgeable article. Thanks for sharing your valuable knowledge.

1
D

Thank you!!

Flutter

Part 2 of 11

In this series, I will talk about Flutter and building application with it. I will be sharing my learnings and experiments with Flutter.

Up next

Building Custom TabBar Indicator in Flutter

A quick tutorial on building a custom tab bar indicator in Flutter.