Ali Qanbari
Ali Qanbari

Reputation: 3121

How to get the number of routes in Navigator's stack

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?

Upvotes: 1

Views: 3193

Answers (4)

Vivek
Vivek

Reputation: 4886

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.

Upvotes: 2

Ahmed Osama
Ahmed Osama

Reputation: 812

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();

Upvotes: 6

Aakash Kumar
Aakash Kumar

Reputation: 1187

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;
  }

Upvotes: 0

Sahandevs
Sahandevs

Reputation: 1160

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;
  }

Upvotes: 3

Related Questions