Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is onWillPop in WillPopScope ignored when using Navigator.pop?

Tags:

flutter

dart

I use a WillPopScope to try to stop a route from popping:

WillPopScope(
  onWillPop: () async {
    print('This is never called');
    return false;
  }
)

When I use Navigator.pop, the current route is simply popped instead of onWillPop being called:

Navigator.of(context).pop();
like image 495
creativecreatorormaybenot Avatar asked May 04 '20 21:05

creativecreatorormaybenot


People also ask

What does Navigator POP do in Flutter?

Pop the top-most route off the navigator that most tightly encloses the given context. The current route's Route. didPop method is called first. If that method returns false, then the route remains in the Navigator's history (the route is expected to have popped some internal state; see e.g. LocalHistoryRoute).

How do I use onWillPop?

In the onWillPop callback, we'll do two things: Display an alert dialog to the user with a question and ask them to click an action button (either Yes or No) Use the response from the dialog to pop the ContentView.

What is navigator of in Flutter?

In Flutter these elements are called routes and they're managed by a Navigator widget. The navigator manages a stack of Route objects and provides two ways for managing the stack, the declarative API Navigator. pages or imperative API Navigator. push and Navigator.


1 Answers

This is by design.

You will have to use Navigator.maybePop:

Tries to pop the current route of the navigator that most tightly encloses the given context, while honoring the route's Route.willPop state.

This means that only Navigator.maybePop honors onWillPop and Navigator.pop does not:

Navigator.of(context).maybePop();
like image 140
creativecreatorormaybenot Avatar answered Nov 15 '22 07:11

creativecreatorormaybenot