Flutter桌面:如何抓住关闭按钮



我正在使用flutter(Windows(的桌面应用程序,如果用户试图用关闭按钮关闭窗口,我需要设置AlertDialog。

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

我在下面附上了一张参考图片。

此按钮

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-关闭之前

目前没有内置的钩子可以让您处理关闭窗口的尝试;请参阅本期。您需要自己实现它,方法是向win32_window.cpp添加一个WM_CLOSE处理程序,取消关闭,用MethodChannel(或其他类似机制(调用Dart,然后如果Dart的响应指示窗口应该关闭,则直接销毁它。

您可以使用这个包bitsdojo_window,在这个按钮CloseWindowButton(colors: closeButtonColors),中,您可以添加一个onPressed回调,让您完全控制启动对话框,或者在调用appWindow.close()之前运行清理代码

最新更新