Here’s a guide on how to use Navigator.push()
and Navigator.pop()
in Flutter using active voice:
What is Navigator in Flutter?
Navigator is a class in Flutter that manages a stack of route objects and allows developers to navigate between them.
A route represents a single screen in a Flutter application. When a new route is pushed onto the stack, it becomes the current route and is displayed on the screen.
Using Navigator.push()
to navigate to a new screen:
Navigator.push()
is a method that pushes a new route onto the stack and displays it on the screen. Here’s how you can use it:
Navigator.push(
context,
MaterialPageRoute(builder: (context) => NewScreen()),
);
In the above example, context
is the BuildContext of the current screen, and NewScreen()
is the widget that represents the new screen you want to navigate to.
Using Navigator.pop()
to return to the previous screen:
Navigator.pop()
is a method that removes the current route from the stack and returns to the previous route. Here’s how you can use it:
Navigator.pop(context);
In the above example, context
is the BuildContext of the current screen.
Using async/await
with Navigator.push()
to handle data returned from a screen:
Sometimes, you may want to pass data between screens or get data back from a screen after it’s been popped from the stack. You can use async/await
with Navigator.push()
to achieve this.
Here’s an example of how you can use async/await
to get data back from a screen:
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => NewScreen()),
);
In the above example, result
is the data returned from the NewScreen()
when it’s popped from the stack.
Read also, How to create Flutter loading indicator?
And that’s it! With these simple steps, you can use Navigator.push()
and Navigator.pop()
to navigate between screens in your Flutter application.