【问题标题】:what is the equivalent method of onbackpressed in flutterFlutter中onbackpressed的等效方法是什么
【发布时间】:2019-06-15 22:08:49
【问题描述】:

我希望在 Flutter 应用程序中使用与 Android 相同的 onBackPressed 逻辑,并且我想在单击手机返回按钮时关闭应用程序。

当我们点击手机返回而不是应用返回按钮时,谁能告诉我如何做到这一点。

机器人:

@Override
public void onBackPressed()
{
     // code here to show dialog
     super.onBackPressed();  // optional depending on your needs
}

【问题讨论】:

标签: android dart flutter


【解决方案1】:

您可以为此使用WillPopScope。 当封闭的ModalRoute(内部与Navigator 一起使用)即将弹出时,它会通知您。它甚至让您可以选择是否要发生流行音乐。

只需将第二个屏幕的Scaffold 包裹在WillPopScope 中。

return WillPopScope(
  onWillPop: () async {
    // You can do some work here.
    // Returning true allows the pop to happen, returning false prevents it.
    return true;
  },
  child: ... // Your Scaffold goes here.
);

【讨论】:

  • 这个解决方案的缺点是iOS上的后退手势不再起作用。
  • 在 Android 设备中使用 WillPopScope 出现黑屏尝试了所有带有导航器的解决方案
【解决方案2】:

希望这会有所帮助...

Future<bool> _onBackPressed() async {
    // Your back press code here...
    CommonUtils.showToast(context, "Back presses");
}

WillPopScope 创建一个小部件,该小部件注册一个回调,以拒绝用户尝试关闭封闭的 ModalRoute。

@override 
Widget build(BuildContext context) {
    return new WillPopScope(
        onWillPop: _onBackPressed,
        child: ...child
    );
}

【讨论】:

【解决方案3】:

您可以使用Navigator.pop(context);Navigator.maybePop(context);

maybePop可以被WillPopScope#onWillPop收听;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 2018-04-02
    相关资源
    最近更新 更多