Flutter Navigation Guide - Push(), Pop() with all required method variants.

Darshan Dalwadi
5 min readJun 24, 2022

--

Hello Readers, Greetings for the day.!

In this article, we will look at Navigation in Flutter from basic to advance methods, be ready with your cup of coffee.

Let’s start with zero, what is Navigation?

In Simple words, Navigation is a mechanism to redirect from one page/ screen/route to another page/screen/route. It is applicable to any kind of application whether it is a Desktop application, Web application, Android, and iOS. Traversing from one screen to another screen with or without data is a basic need of any application.

Photo by Monty Allen on Unsplash

Here we will talk about mobile apps, so in any general mobile application, there is a stack behind the scene, which maintains pages or routes of the app. In flutter, this stack is managed by the Navigator widget(API). It manages a stack of Routes(pages) and provides methods for navigating in forward and backward directions.

A MaterialApp OR CupertinoApp is the simplest way to set things up for any flutter app. The first page(it can be any page like the login page or home page) will reside at the bottom of the Navigation route stack.

In the simple terms:
Navigator -
You can say, it's a widget that manages a stack of Route objects. Route - Consider its as an object, managed by a Navigator - that represents a screen. There is a class named Route is available with Flutter, and it has two popular implementations, MaterialPageRoute and CupertinoPageRoute.

As navigator uses stack discipline so there are majorly two types of operations performed over the stack, PUSH and POP.

So let’s start with push() operations first, below are the push() methods that we are going to cover in this article.

  • push()
  • pushNamed()
  • pushAndRemoveUntil() & pushNamedAndRemoveUntil()
  • popAndPushNamed()
  • pushReplacement() & pushReplacementNamed()

push():
Like its name, it simply navigates to the next page by pushing the given Route to the navigation stack. That will show you the next screen on the device.

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

push() with arguments:
You can also pass arguments (any type of object) to the next screen, please take a look at the below snippet.

Navigator.push( context, 
MaterialPageRoute(builder: (context) { return const NextScreen();},
settings: RouteSettings(arguments: {‘email’:email}))
);

pushNamed():
It is an easy way to navigate without remembering the typical screen name of each route/page, you can define an alternate name for each route and use them anywhere inside the app.
To do this, you need to register your route names with the routes:{ } attribute of your MaterialApp widget as below:

MaterialApp(
initialRoute: "/",
routes: {
"/" : (context) => const HomeScreen(),
"/gallery-screen" : (context) => const GalleryScreen(),
}
);

Inside your HomeScreen, write the below snippet to go to the GalleryScreen:

Navigator.push(context,”/gallery-screen”);

pushNamed() with arguments:
Navigate using the route name along with the arguments. Here we are passing the email to the next screen.

Navigator.push(context, 
”/screen2”, arguments: {‘email’:’darshan@gmail.com’}
);

Now, the question arise is, how to get this passed arguments in the next screen? Whether it is passed via push() or pushNamed()…. So the answer is using ModalRoute class.

final arguments = 
ModalRoute.of(context)!.settings.arguments as Map<String, String>;
print(argumets[‘email’] ?? “Default value”);

pushAndRemoveUntil() & pushNamedAndRemoveUntil():
Iterate to find the given route in the Navigator stack, and then remove all the previous routes until the predicate returns true.
UseCase: After logging out from the app, a user should be redirected to a login screen (or any screen that is decided to be displayed) in such cases.

Navigator.pushAndRemoveUntil(context,
MaterialPageRoute(builder: (context) {return const SecondScreens();}), (route) => false);
---------------------------------------------------Navigator.pushNamedAndRemoveUntil (context,
“/login-screen”,
(route) => false);

popAndPushNamed():
Pop the current/standing route off from the stack, and push a given named route in its place.
Use-case:
The Shopping app CategoryListScreen, displays a list of the categories, and there is also a FilterCategoryScreen, in which users can apply the filters. So, after applying the filter when a user saves the changes on the “Apply Changes” button, the FiltersScreen should be popped out and the user will again show the ProductsListScreen with the new filter values.

Navigator.popAndPushNamed(context, “/home-screen”);

pushReplacement() & pushReplacementNamed():
Replace the current route from a navigator, by pushing the given route. When you want to display a page only a single time, you can use this method. It will execute the enter animation for a given screen.
Example:
SplashScreen should only be visible once in the app lifecycle when a user moved ahead it should not come into the picture again. The second example is based on the login screen, which means after logging in successfully, a user will be landing on the DashboardScreen, and you don’t want the user to go back to LoginScreen in any case. So, login route should be completely replaced by the dashboard route.

Navigator.pushReplacement(context,
MaterialPageRoute (builder: (context) {return SecondScreen();})
);
Navigator.of(context).pushReplacementNamed(‘/Second-screen’);

What is the need of passing “context” in Navigations:
Context : is a description of a widget in a widget tree, each widget has its own context. It is necessary to know for an app that on which widget you want traverse.

Hope, the push() methods are clear with code. Now, will take a look on pop() methods. Below are the methods that we will see in action.

  • pop()
  • popUntil()
  • popAndPushedNamed()
  • canPop()
  • maybePop()

pop():
To navigate back to the previous page. It simply removes the current page from the navigation stack.

Navigator.pop(context);

pop() with arguments:
To navigate back to the previous page with arguments. In your second-screen you need to use pop() method with arguments like the below code snippet.

Navigator.pop(context, objectWantToPass);

How to fetch data back on the previous screen using pop(). In firstScreen you need to use the below code snippet to get data back from the secondScreen.

Future<void> _getResultFromNextScreen(BuildContext context) async { final result = await Navigator.push(context,
MaterialPageRoute(builder: (context) => const SecondScreen()));
log($result); //import ‘dart:developer’ to use logging.
}

Here method returns a Future object, that represents the result of an asynchronous operation. Execution will wait for the function’s asynchronous operation to complete or to throw an error if function fails by any reason.

popUntil():
It will call pop() repeatedly over the stack until it removes the given page name.
Use-case:
Suppose you’ve some functionality that is spread through 3 to 4 screens and suppose the user wants to terminate that process at the last screen. So user should redirect to the dashboard page by removing all the middle (3 to 4)pages, at that time you can think of popUntil().

Navigator.popUntil(context, ModalRoute.withName(“/Dashboard”));

popAndPushedNamed():
It will replace the current page/route with a given named route in the stack.
Use-case:
Think about the example of productList and filter screen. From productList you want to show a filter page and then after applying a filter, you need to remove the filter page from the stack completely and need to show productList page again.

Navigator.popAndPushNamed(context,”/Screen4");

canPop():
It checks whether a given route can be popped or not, This function returns true only if popping the navigator would not remove the initial route/(root widget of the widget tree). Means will return true only if the passed route is not the initial route.

Navigator.canPop(context);

maybePop():
Now, what if you are on the initial Route and somebody mistakenly tried to pop this screen. Popping the only screen on the stack would close your app. So, it will check whether this is the only available route or not? If not, then it will return true.

Navigator.maybePop(context);

Thank You!, Hope you enjoy and got some help from this article. You can always write me on dalwadidarshan83@gmail.com for any queries or concerns.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Darshan Dalwadi
Darshan Dalwadi

Written by Darshan Dalwadi

Trust your self and you will rock.!

Responses (1)

Write a response