Navigator.push
- Flutter course
- Beginner
- Lesson 87/99
- 4 min
Open a new screen with Navigator.push.
What is Navigator.push?
Navigator.push opens a new screen by adding a new route to the stack. The first parameter is context and the second is the route to open. The route is usually created as a MaterialPageRoute.
Navigator.push(
context,
MaterialPageRoute(builder: (_) => SecondScreen()),
);The context parameter
The context parameter tells Navigator the position of the call in the widget tree. When called from a Scaffold or similar widget, context is usually taken from the parameter of the build method. Without context, Navigator cannot know which page the call came from.
Practice Open a second screen with Navigator.push
Write a function ac that prints Ekran acildi. Write a StatelessWidget named IkinciEkran. In main call ac. Have an ElevatedButton on the first screen whose onPressed opens IkinciEkran with Navigator.push.
Starter code
import 'package:flutter/material.dart';
// ac fonksiyonu yaz: "Ekran acildi" yazdirsin
// IkinciEkran adinda bir StatelessWidget yaz
void main() {
// ac'i cagir
runApp(const Uygulama());
}
class Uygulama extends StatelessWidget {
const Uygulama({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
// ElevatedButton ekle
child: SizedBox(),
),
),
);
}
}Sample solution
import 'package:flutter/material.dart';
void ac() {
print('Ekran acildi');
}
class IkinciEkran extends StatelessWidget {
const IkinciEkran({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text('Ikinci')));
}
}
void main() {
ac();
runApp(const Uygulama());
}
class Uygulama extends StatelessWidget {
const Uygulama({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => const IkinciEkran()),
);
},
child: const Text('Ac'),
),
),
),
);
}
}Expected output
Ekran acildi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Navigator.push do?
- Rebuilds the screen
- Adds a new screen to the stack Correct answer
- Opens the keyboard
- Removes the top screen
Explanation: Navigator.push opens a new screen by adding a new route to the stack; it does not remove a screen, rebuild, or open the keyboard.
2 Add the push method
Navigator.____(context, MaterialPageRoute(builder: (_) => Scaffold()));
Navigator.push(context, MaterialPageRoute(builder: (_) => Scaffold()));
Explanation: To open a new screen, the Navigator.push method is used; pop closes a screen, and replace and remove do different operations.
3 push parameters
| Term | Meaning |
|---|---|
Navigator.push |
Opens a new screen |
context |
Widget tree position |
MaterialPageRoute |
Creates a route |
builder |
Builds the screen |