Flutter桌面软件开发中使用window_manager 实现点击关闭隐藏到托盘

发布于 1 年前 作者 phonegap100 809 次浏览 最后一次编辑是 1 年前 来自 分享

Flutter桌面软件开发中使用window_manager 实现点击关闭隐藏到托盘 macos额外配置

提示:win无需配置

如果你需要使用 hide 方法,你需要禁用 QuitOnClose。

macOS
更改文件 macos/Runner/AppDelegate.swift 如下:

import Cocoa
import FlutterMacOS

@NSApplicationMain
class AppDelegate: FlutterAppDelegate {
  override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
-    return true
+    return false
  }
}

关闭前确认

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 {
    // 添加此行以覆盖默认关闭处理程序
    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();
                  
                  await windowManager.hide();  //隐藏到托盘
                },
              ),
            ],
          );
        },
      );
    }
  }
}
回到顶部