Navigation Methods in Flutter
Introduction
In this section, you will learn about useful navigation methods in Flutter. Here are some useful navigation methods:
Navigator.push()
Navigator.push() is used to navigate to a new screen by pushing it onto the navigation stack.
Example 1: Using Navigator.push()
In this example below, you will learn how to navigate to a new screen using Navigator.push().
// Navigator.push example
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AboutScreen()),
);
Navigator.pushNamed()
Navigator.pushNamed() is used to navigate to a new screen using a named route. Named routes are routes that are named using a string.
Example 2: Using Navigator.pushNamed()
In this example below, you will learn how to navigate to a new screen using Navigator.pushNamed().
Navigator.pushNamed(context, '/about');
Navigator.pop()
Navigator.pop() is used to return to the previous screen, effectively popping the current screen off the navigation stack. It’s akin to the back button on a device.
Example 3: Using Navigator.pop()
Navigator.pop(context);
Navigator.pushReplacement()
This method replaces the current screen with a new one on the navigation stack, which is useful in scenarios like a login flow where you do not want the user to return to the login screen.
Example 4: Using Navigator.pushReplacement()
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => HomeScreen()),
);
Navigator.pushAndRemoveUntil()
Navigator.pushAndRemoveUntil() pushes a new screen and removes all the previous screens until a certain condition is met. This method is handy for logging out a user, where you want to remove all screens from the stack and navigate back to the login screen.
Example 5: Using Navigator.pushAndRemoveUntil()
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => WelcomeScreen()),
(Route<dynamic> route) => false,
);