Navigator.pop
- Flutter course
- Beginner
- Lesson 89/99
- 4 min
Go back to the previous screen with Navigator.pop.
What is Navigator.pop?
Navigator.pop removes the topmost route from the stack and returns to the previous screen. The first parameter is context. If push was used to open a new screen, pop is used to go back.
Navigator.pop(context);pop and stack behavior
When Navigator.pop is called, the topmost screen is removed and the screen below becomes visible. If there is only one screen in the stack, pop can cause the app to close. Therefore, it is safe to use pop when there are at least two screens. If a second parameter is given, it returns to the caller as the result.
Practice Go back with Navigator.pop
Write a function kapat that prints Ekran kapandi. In main call kapat. Add an ElevatedButton whose onPressed calls Navigator.pop(context).
Starter code
import 'package:flutter/material.dart';
// kapat fonksiyonu yaz: "Ekran kapandi" yazdirsin
void main() {
// kapat'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 kapat() {
print('Ekran kapandi');
}
void main() {
kapat();
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.pop(context);
},
child: Text('Kapat'),
),
),
),
);
}
}Expected output
Ekran kapandi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which screen is closed when Navigator.pop is called?
- The topmost screen in the stack Correct answer
- The bottommost screen in the stack
- The first screen
- All screens
Explanation: Navigator.pop removes the topmost screen in the stack; it does not close the bottommost, first or all screens.
2 Add the context parameter
Navigator.pop(____, 'Sonuc');
Navigator.pop(context, 'Sonuc');
Explanation: The first parameter of Navigator.pop is context; route, screen or widget are not valid parameter values.
3 pop parameters
| Term | Meaning |
|---|---|
Navigator.pop |
Closes the top screen |
context |
pop's first parameter |
result |
Value returned to caller |
stack |
Sequence of screens |