且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检测用户是否将当前页面留在Flutter中?

更新时间:2023-11-29 15:47:52

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

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.
);