Is there a way to know if the current page is the last page in the Navigator Stack and calling Navigator.pop()
at this point will close the app?
Asked
Active
Viewed 2,197 times
1

Ali Qanbari
- 2,923
- 1
- 12
- 28
4 Answers
5
You can use this code to check if the route is the first :
ModalRoute.of(context).isFirst
so the full code will be
if(! ModalRoute.of(context).isFirst)
Navigator.pop();

Ahmed Osama
- 672
- 1
- 8
- 15
3
It doesn't close the app it destroys the last route shows a black screen.
you can close the app using this: Flutter how to programmatically exit the app
and you can't access the stack or history because it's private in Navigator class Navigator._history
but you can use this workaround to check if the current route is the last one or not:
Future<bool> isCurrentRouteFirst(BuildContext context) {
var completer = new Completer<bool>();
Navigator.popUntil(context, (route) {
completer.complete(route.isFirst);
return true;
});
return completer.future;
}

Sahandevs
- 1,120
- 9
- 25
2
I found this in the source of the AppBar
widget.
final ModalRoute<dynamic>? parentRoute = ModalRoute.of(context);
final bool canPop = parentRoute?.canPop ?? false;
When canPop
is false
, you are on the root screen.

Vivek
- 4,786
- 2
- 18
- 27
0
If you just want to handle something before the application exits. Like showing an confirm dialog you could use WillPopScope
.
Example
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _showDialog,
child: Scaffold(
body: Center(
child: Text("This is the first page"),
),
),
);
}
Future<bool> _showDialog() {
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("Are you sure?"),
content: Text("You want to exit app"),
actions: <Widget>[
FlatButton(
child: Text("Yes"),
onPressed: () => Navigator.of(context).pop(true),
),
FlatButton(
child: Text("No"),
onPressed: () => Navigator.of(context).pop(false),
)
],
);
}) ?? false;
}

Aakash Kumar
- 1,069
- 7
- 11
-
this is not what I'm looking for. I'm looking for a better answer for this question https://stackoverflow.com/questions/58000349/i-open-the-app-through-the-notification-and-want-to-keep-it-open-after-the-user/58004051#58004051 that wants to open the main page when the route stack is empty. – Ali Qanbari Sep 19 '19 at 08:09