检测用户是否将当前页面留在Flutter中? [英] Detect if the user leaves the current page in Flutter?

查看:50
本文介绍了检测用户是否将当前页面留在Flutter中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以检测用户是否离开当前页面?我认为 WidgetsBinding 无效,因为它可以自行处理这些事件.那么,有人有什么解决方案吗?感谢您的帮助.

Is there any way to detect if the user leaves the current page? I don’t think WidgetsBinding will work, because it handles these events by itself. So, does anyone have any solution? Any help is appreciated.

推荐答案

如果通过离开页面"表示用户从该页面退回",我有一个简单的解决方案.如果您还希望在用户打开当前页面之前的另一页面时得到通知,则以下解决方案将不起作用.

I have an easy solution if by "leaving the page" you mean that the user goes "back" from this page. The following solution will not work if you also want to get notified if the user opens up another page in front of the current one.

对于第一种情况,您可以使用 WillPopScope .当要封闭的 ModalRoute (由 Navigator 内部使用)时,此类会通知您.甚至让您可以选择是否要弹出.

For the first case, you could use a WillPopScope. It's a class that notifies you when the enclosing ModalRoute (internally used by the Navigator) is about to be popped. It even leaves you a choice to whether or not you want the pop to happen.

只需将第二个屏幕的 Scaffold 包装在 WillPopScope 中.

Just wrap the second screen's Scaffold in a 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.
);

这篇关于检测用户是否将当前页面留在Flutter中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆