flutter给聊天软件的桌面做一个退出事件
Contents
我需要给聊天软件的桌面做一个退出事件。移动端是有WillPopScope组件的。桌面端我使用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() {
super.initState();
windowManager.addListener(this);
_init();
}
@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();
},
),
],
);
},
);
}
}
}
拿到我的代码之下适配一下:
-
混入窗口继承:
... with WindowListener { -
加入初始化:
@override void initState() { if (isDesktop) { windowManager.addListener(this); _init(); } super.initState(); }
Future<void> _init() async {
await windowManager.setPreventClose(true);
setState(() {});
}
- 加入despose事件:
@override
void dispose() {
if (isDesktop) {
windowManager.removeListener(this);
}
super.dispose();
}
-
加入关闭窗口事件:
@override Future<void> onWindowClose() async { bool isPreventClose = await windowManager.isPreventClose(); if (isPreventClose) { print("关闭窗口事件"); await windowManager.destroy(); } super.onWindowClose(); }
这样点击窗口的关闭按钮就会触发事件了。
