flutter 桌面 : How to catch closure button?

标签 flutter event-handling flutter-desktop

我正在使用 flutter (Windows) 开发桌面应用程序,如果用户尝试使用关闭按钮关闭窗口,我需要设置一个 AlertDialog。

如果有人有想法甚至解决方案,我会采纳 :D

我在下面附上了一张引用图片。

This button

最佳答案

window_manager 现在支持这个。

import 'package:flutter/cupertino.dart';
import 'package:window_manager/window_manager.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WindowListener {
  @override
  void initState() {
    windowManager.addListener(this);
    _init();
    super.initState();
  }

  @override
  void dispose() {
    windowManager.removeListener(this);
    super.dispose();
  }

  void _init() async {
    // Add this line to override the default close handler
    await windowManager.setPreventClose(true);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    // ...
  }

  @override
  void onWindowClose() async {
    bool _isPreventClose = await windowManager.isPreventClose();
    if (_isPreventClose) {
      showDialog(
        context: context,
        builder: (_) {
          return AlertDialog(
            title: Text('Are you sure you want to close this window?'),
            actions: [
              TextButton(
                child: Text('No'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              TextButton(
                child: Text('Yes'),
                onPressed: () {
                  Navigator.of(context).pop();
                  await windowManager.destroy();
                },
              ),
            ],
          );
        },
      );
    }
  }
}

https://github.com/leanflutter/window_manager#confirm-before-closing

关于 flutter 桌面 : How to catch closure button?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63115627/

相关文章:

dart - 仅运行 flutter 桌面应用程序的单个实例

flutter - 底部导航栏在 flutter 中过渡

event-handling - 如何在场景图的节点中监听 WindowEvent.WINDOW_SHOWN?

javascript - 有没有办法在不先声明数据参数的情况下访问 knockout 按键绑定(bind)中的第二个事件参数?

visual-studio - 无法找到合适的 Visual Studio 工具链。请运行 `flutter doctor` 了解更多详情

flutter - 如何将焦点固定在 Flutter 中的 ListView 项目上?

flutter - 如何在 flutter Streambuilder 中重启流?

flutter - 我可以用 Provider 包装 MaterialApp 小部件吗?

flutter - 水平滑动标签栏

javascript - 如何获取调用 Javascript 函数的控件?