简体   繁体   English

"Flutter iOS Back Swipe 不调用 onWillPop"

[英]Flutter iOS Back Swipe does not call onWillPop

I covered my Scaffold with a WillPopScope , but the onWillPop callback is not called when swiping to go back on iOS.我用WillPopScope覆盖了我的Scaffold ,但是在滑动返回 iOS 时不会调用onWillPop回调。
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...
        ],
      ),
    ),
  );
}

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).我找到了原因:WillPopScope 不起作用,因为上面构建方法的widget 不是top widget(main 调用的widget)。 I hope it helps others.我希望它可以帮助其他人。

this is a problem and discussed a lot in this issue but there is a way to fix it and it is to use this package这是一个问题,在这个问题中讨论了很多,但有一种方法可以解决它,那就是使用这个包

return ConditionalWillPopScope(
child: _MyScreenContent(),
onWillPop: _onWillPop,
shouldAddCallbacks: _hasChanges,
 );

As it is mentioned here here<\/a> , to make your WillPopScope<\/strong> work, you should override hasScopedWillPopCallback<\/strong> getter in MaterialPageRoute<\/strong> like this:正如本文所提到这里<\/a>,让你的工作WillPopScope,<\/strong>你应该重写hasScopedWillPopCallback<\/strong>吸气剂MaterialPageRoute<\/strong>这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM