Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter iOS Back Swipe does not call onWillPop

Tags:

flutter

dart

I covered my Scaffold with a WillPopScope, but the onWillPop callback is not called when swiping to go back on iOS.
What could be the reason for this?

@override
Widget build(BuildContext context) {
  return WillPopScope(
    onWillPop: () async {
      print("onWillPop"); // is not printed to the console
      if (Navigator.of(context).userGestureInProgress)
        return false;
      else
        return true;
    },
    child: new Scaffold(
      appBar: new AppBar(
        title: new Text("App Title"),
      ),
      body: Stack(
        children: <Widget>[
          ...widgets...
        ],
      ),
    ),
  );
}
like image 638
ahmet ay Avatar asked Nov 16 '22 03:11

ahmet ay


2 Answers

As it is mentioned here, to make your WillPopScope work, you should override hasScopedWillPopCallback getter in MaterialPageRoute like this:

class CustomMaterialPageRoute extends MaterialPageRoute {
  @protected
  bool get hasScopedWillPopCallback {
    return false;
  }
  CustomMaterialPageRoute({
    @required WidgetBuilder builder,
    RouteSettings settings,
    bool maintainState = true,
    bool fullscreenDialog = false,
  }) : super(
          builder: builder,
          settings: settings,
          maintainState: maintainState,
          fullscreenDialog: fullscreenDialog,
        );
}

And then replace MaterialPageRoute on CustomMaterialPageRoute in your Router. It definitely make WillPopScope work for both IOS and Android platforms for sure.

like image 139
RuslanBek Avatar answered Jun 14 '23 03:06

RuslanBek


I found the reason: WillPopScope does not work because the widget with the above build method is not a top widget (the widget called by main). I hope it helps others.

like image 40
ahmet ay Avatar answered Jun 14 '23 02:06

ahmet ay