Flutter系统托盘

发布于 1周前 作者 phonegap100 来自 分享

Flutter开发桌面软件的时候经常需要配置系统托盘,如下图所示

381633085.bmp

接下来我们就一起看看Flutter如何实现系统托盘

配置系统托盘可以使用system_tray 也可以使用tray_manager,这里主要给大家讲讲system_tray,tray_manager使用方法类似

https://pub.dev/packages/system_tray

https://pub.dev/packages/tray_manager

1、安装依赖

dependencies:
  system_tray: ^2.0.2

2、pubspec.yaml配置 tray对应的图标

  assets:
    - assets/tray.png
    - assets/tray.ico

或者加载所有文件

  assets:
    - assets/

3、配置底部tray

1、新建tray.dart

import 'dart:io';
import 'package:system_tray/system_tray.dart';

Future<void> initSystemTray() async {
  String path = Platform.isWindows ? 'assets/tray.ico' : 'assets/tray.ico';

  final AppWindow appWindow = AppWindow();
  final SystemTray systemTray = SystemTray();

  // 初始化SystemTray
  
  await systemTray.initSystemTray(
    title: "system tray",
    iconPath: path,
  );

  // 创建Menu
  final Menu menu = Menu();
  await menu.buildFrom([
    MenuItemLabel(label: 'Show', onClicked: (menuItem) => appWindow.show()),
    MenuItemLabel(label: 'Hide', onClicked: (menuItem) => appWindow.hide()),
    MenuItemLabel(label: 'Exit', onClicked: (menuItem) => appWindow.close()),
  ]);

  // 创建 context menu
  
  await systemTray.setContextMenu(menu);

  // 处理system tray 事件
  systemTray.registerSystemTrayEventHandler((eventName) {
    print("eventName: $eventName");
    if (eventName == kSystemTrayEventClick) {
      Platform.isWindows ? appWindow.show() : systemTray.popUpContextMenu();
    } else if (eventName == kSystemTrayEventRightClick) {
      Platform.isWindows ? systemTray.popUpContextMenu() : appWindow.show();
    }
  });
}

2、main.dart中初始化

void main() async {
  //必须配置
  WidgetsFlutterBinding.ensureInitialized();
  //初始化Tray
  await initSystemTray();
}

某些插件(如sqflite)需要使用WidgetsFlutterBinding.ensureInitialized()方法,因为它们需要访问特定于平台的通道才能正常工作

回到顶部