Home > Enterprise >  Why does WillPopScope always disable swipe backwards?
Why does WillPopScope always disable swipe backwards?

Time:12-02

When pushing on a new screen and wanting to disable the ability to swipe backwards I found the WillPopScope widget.

WillPopScope(
      onWillPop: () async => false,
      child: <some child>

however, it prevents the swipe gesture regardless of whether or not I return true of false. Is it possible to tell this widget that it can pop back on certain screen states?

So effectively I would have:

WillPopScope(
      onWillPop: () async => widget._canSwipeBack,
      child: <some child>

Right now I have add/not-add the widget based on the screen state which seems quite odd.

CodePudding user response:

Please refer to the below code

Without wrapping the widget with WillPopScope usually its performs Navigator.pop(context);

// disables swiping back
WillPopScope(
// disables swiping back or navigating back
 onWillPop: () {},
child: Scaffold(
body: Container(),
  ),
);


WillPopScope(
  onWillPop: () {
   // whenever you want to navigate back to specific route
    Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SecondRoute()),
    );
 },
 child: Scaffold(
   body: Container(),
  ),
);

WillPopScope(
  onWillPop: () {
// pop back
      Navigator.pop(context);
        },
child: Scaffold(
body: Container(),
  ),
);

  • Related