Flutter系统托盘管理插件systray的使用

Flutter系统托盘管理插件systray的使用

Sonr 创作者 The Sonr App 提供

pub points


Flutter Systray 是一个用于 go-flutter-desktop 的插件,使桌面 Flutter 应用支持系统托盘菜单。该插件通过 trayhost 支持 MacOSWindowsLinux 平台。

  • 此插件实现的功能有限。目前不支持子菜单和复选框等。欢迎提交 PR。
  • 别忘了检查示例应用!
  • 该插件是从 Janez Štupar 叉过来的。

🔷 安装

Dart

标准实现方式:

dependencies:
    sonr_ble: ^0.0.1
Golang

此 Go 包实现了 Flutter sonr_ble 插件的主机端。

导入后,在你的 go-flutter 应用程序选项 中添加以下选项:

import "github.com/sonr-io/systray"

/// ....
/// ....

flutter.AddPlugin(&systray.SystrayPlugin{})

🔷 示例

以下是初始化系统托盘菜单并为其添加一个焦点动作的示例,该动作会将 Flutter 应用程序窗口带到前台。

MainEntry main = MainEntry(
  title: "title",
  iconPath: path,
);

Systray.initSystray(main).then((result) {
    Systray.updateMenu([
      SystrayAction(
          name: "focus",
          label: "Focus",
          tooltip: "Bring application window into focus",
          iconPath: '',
          actionType: ActionType.Focus),
    ]);
});
  • MainEntry - 代表系统托盘菜单的根节点。它可以有一个图标(适用于 Windows、Linux、Mac)或/和标题和工具提示(适用于 Mac)。
  • SystrayAction - 系统托盘菜单项的列表。这些项目可以有图标、标题和工具提示。名称作为唯一标识符。

要更改菜单项,我们可以调用 updateMenu 函数,注意 updateMenu 会替换现有的菜单项:

Systray.updateMenu([
SystrayAction(
    name: "counterEvent",
    label: "Counter event",
    tooltip: "Will notify the flutter app!",
    iconPath: '',
    actionType: ActionType.SystrayEvent),
SystrayAction(
    name: "systrayEvent2",
    label: "Event 2",
    tooltip: "Will notify the flutter app!",
    iconPath: '',
    actionType: ActionType.SystrayEvent),
SystrayAction(
    name: "quit", label: "Quit", tooltip: "Close the application", iconPath: '', actionType: ActionType.Quit)
]);

我们还可以为由系统托盘触发的事件注册回调处理器:

Systray systemTray = FlutterSystray.init();
systemTray.registerEventHandler("counterEvent", () {
  setState(() {
    _counter += 1;
  });
});

Flutter Systray 通过 SystrayAction.name 属性匹配回调。

可用的系统托盘操作

目前 Flutter Systray 支持三种类型的操作,允许你调用平台操作并在 Flutter 应用程序中触发自定义事件:

enum ActionType {
  Quit, // 操作将触发应用程序关闭
  Focus, // 操作将触发 GLFW `window.Show` 并将 Flutter 应用程序带到前台
  SystrayEvent // 操作将触发一个事件,该事件将在 Flutter 应用程序中调用已注册的回调
}

🔷 许可证

MIT 许可证


示例代码

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:systray/systray.dart';
import 'package:path/path.dart' as p;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Windows 需要 .ico 文件
  String path;
  if (Platform.isWindows) {
    path = p.absolute('go\\assets', 'icon.ico');
  } else {
    path = p.absolute('go/assets', 'icon.png');
  }

  // 系统托盘菜单的根节点
  MainEntry main = MainEntry(
    title: "title",
    iconPath: path,
  );

  // 我们首先初始化系统托盘菜单,然后添加菜单项
  await Systray.initSystray(main);
  await Systray.updateMenu([
    SystrayAction(
        name: "focus",
        label: "Focus",
        actionType: ActionType.Focus),
    SystrayAction(
        name: "counterEvent",
        label: "Counter event",
        actionType: ActionType.SystrayEvent),
    SystrayAction(
        name: "systrayEvent2",
        label: "Event 2",
        actionType: ActionType.SystrayEvent),
    SystrayAction(
        name: "quit", label: "Quit", actionType: ActionType.Quit)
  ]);

  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  // 注册一个事件处理器
  final Systray systemTray = Systray.init();

  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _counter = 0;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter systray example app'),
        ),
        body: Center(
          child: Text(
              'There should be a menu with a Hover icon in the systray.\n\n Number of times that the counter was triggered: $_counter '),
        ),
      ),
    );
  }

  [@override](/user/override)
  void initState() {

    // 设置一个回调处理系统托盘触发的事件
    widget.systemTray.registerEventHandler("counterEvent", () {
      setState(() {
        _counter += 1;
      });
    });

    super.initState();
  }
}

更多关于Flutter系统托盘管理插件systray的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter系统托盘管理插件systray的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中,如果你想使用系统托盘(System Tray)功能,可以使用 systray 插件。这个插件允许你在桌面应用程序中创建和管理系统托盘图标,并添加菜单项。以下是如何使用 systray 插件的基本步骤。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 systray 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  systray: ^0.0.1+1  # 请检查最新版本

然后运行 flutter pub get 来获取依赖。

2. 导入包

在你的 Dart 文件中导入 systray 包:

import 'package:systray/systray.dart';

3. 创建系统托盘图标

你可以使用 Systray 类来创建和管理系统托盘图标。以下是一个简单的示例:

import 'package:flutter/material.dart';
import 'package:systray/systray.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('System Tray Example'),
        ),
        body: Center(
          child: Text('Check the system tray!'),
        ),
      ),
    );
  }
}

class SystemTrayManager {
  final Systray _systray = Systray();

  SystemTrayManager() {
    _initSystemTray();
  }

  void _initSystemTray() async {
    await _systray.init(
      iconPath: 'assets/icon.png', // 图标路径
      tooltip: 'Flutter System Tray',
    );

    // 添加菜单项
    _systray.addMenuItem(
      label: 'Open',
      onClicked: () {
        print('Open clicked');
      },
    );

    _systray.addMenuItem(
      label: 'Exit',
      onClicked: () {
        _systray.dispose();
        // 退出应用程序
        // exit(0);
      },
    );
  }
}

4. 初始化系统托盘

在你的应用程序启动时初始化系统托盘:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SystemTrayManager();
  runApp(MyApp());
}

5. 添加图标资源

确保你在 pubspec.yaml 文件中添加了图标资源:

flutter:
  assets:
    - assets/icon.png

6. 处理菜单项点击

addMenuItem 方法中,你可以为每个菜单项提供一个 onClicked 回调函数,用于处理用户点击菜单项时的操作。

7. 释放资源

在应用程序退出时,记得调用 dispose 方法来释放系统托盘资源:

_systray.dispose();
回到顶部