I want to detect when a user tries to leave the current page and probably stop them from doing so in flutter.


Solution 1: Tonny Bawembye

welcome to stack overflow, You can achieve this by using the WillPopScope Widget. Below is a code sample to achieve this.

WillPopScope(
          child: Container(),
          onWillPop: () {
            if (allowPop) {
              return Future.value(true);
            } else {
              return Future.value(false);
            }
          });

Where allowPop can be a variable you can use to check if to allow user to leave the page or not.


Solution 2: Rashid Wassan

You can do this with the help of WillPopScope.

return WillPopScope(
  onWillPop: () async {
    // returning false will don't let screen pop.
    return false;
  },
  child: ... // Your Scaffold goes here.
);