【问题标题】:Flutter iOS Back Swipe does not call onWillPopFlutter iOS Back Swipe 不调用 onWillPop
【发布时间】:2019-08-05 10:38:25
【问题描述】:

我用WillPopScope 覆盖了我的Scaffold,但是在滑动返回iOS 时不会调用onWillPop 回调。
这可能是什么原因?

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

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    正如 here 所提到的,要使您的 WillPopScope 工作,您应该像这样覆盖 MaterialPageRoute 中的 hasScopedWillPopCallback getter: p>

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

    然后在 Router 中的 CustomMaterialPageRoute 上替换 MaterialPageRoute。它绝对让 WillPopScope 肯定适用于 IOS 和 Android 平台。

    【讨论】:

      【解决方案2】:

      我找到了原因:WillPopScope 不起作用,因为上面构建方法的小部件不是顶级小部件(main 调用的小部件)。我希望它可以帮助其他人。

      【讨论】:

        【解决方案3】:

        这是一个问题,在issue 中讨论了很多,但有一种方法可以解决它,那就是使用this package

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-08-18
          • 2020-06-02
          • 1970-01-01
          • 2020-12-04
          • 1970-01-01
          • 1970-01-01
          • 2020-10-09
          相关资源
          最近更新 更多