'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?



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sahandevs
Solution 2 Ahmed Osama
Solution 3 Aakash Kumar