有没有办法在关闭浏览器选项卡 运行 flutter 应用程序时显示警告对话框?

Is there a way to show a warning dialog when closing a browser tab running a flutter app?

当用户尝试关闭我的 flutter web 应用程序中的选项卡时,我想向用户表明正在下载一个文件。有没有一种方法可以连接到应用程序以检测此行为并显示此类警告消息?

您可以像这样为 BeforeUnloadEvent 注册代码:

import 'dart:html' as html;

/// Subscription on application termination warning
StreamSubscription? _onBeforeUnloadSubscription;

//enable warning for closing browser tab:
_onBeforeUnloadSubscription = registerOnBeforeUnload("Transfers in progress!");

//disable warning for closing browser tab:
stopBeforeUnloadHandler();


StreamSubscription? registerOnBeforeUnload(String warningMessage) {
  StreamSubscription<html.BeforeUnloadEvent> _onBeforeUnloadSubscription;

  _onBeforeUnloadSubscription = html.window.onBeforeUnload.listen((e) async {
    (e as html.BeforeUnloadEvent).returnValue = warningMessage;
    return Future.value(warningMessage);
  }) as StreamSubscription<html.BeforeUnloadEvent>;
  return _onBeforeUnloadSubscription;
}

void stopBeforeUnloadHandler() {
  if (_onBeforeUnloadSubscription != null) {
    _onBeforeUnloadSubscription!.cancel();
    _onBeforeUnloadSubscription = null;
  }
}