tray_manager Flutter Plugin

repository·main·Indexed 43 days ago

https://github.com/leanflutter/tray_manager

A Flutter plugin for defining and managing system tray icons and context menus on Linux, macOS, and Windows. It provides the TrayManager singleton for controlling icons and menus, and the TrayListener mixin for responding to user interactions such as clicks and menu item selections. Supports platform-specific configurations including macOS icon positioning and Linux AppIndicator requirements.

Tokens
2.7K
Snippets
9
Records
11
Agent score
53%

What's inside tray_manager

  1. Listen to tray events using TrayListener

    main

    To respond to user interactions with the tray (like clicking the icon or selecting a menu item), implement the TrayListener mixin in your StatefulWidget's state.

    1. Add the listener: trayManager.addListener(this); in initState.
    2. Remove the listener: trayManager.removeListener(this); in dispose.
    3. Override methods like onTrayIconMouseDown or onTrayMenuItemClick to handle logic.
    import 'package:flutter/material.dart';
    import 'package:tray_manager/tray_manager.dart';
    
    class HomePage extends StatefulWidget {
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> with TrayListener {
      @override
      void initState() {
        trayManager.addListener(this);
        super.initState();
        _init();
      }
    
      @override
      void dispose() {
        trayManager.removeListener(this);
        super.dispose();
      }
    
      void _init() {
        // ...
      }
    
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    
      @override
      void onTrayIconMouseDown() {
        // example: pop up the menu on click
        trayManager.popUpContextMenu();
      }
    
      @override
      void onTrayIconRightMouseDown() {
        // handle right click
      }
    
      @override
      void onTrayIconRightMouseUp() {
        // handle right mouse up
      }
    
      @override
      void onTrayMenuItemClick(MenuItem menuItem) {
        if (menuItem.key == 'show_window') {
           // handle show window
        } else if (menuItem.key == 'exit_app') {
           // handle exit
        }
      }
    }
  2. Install tray_manager

    main

    Add tray_manager to your pubspec.yaml dependencies.

    Linux Requirements: You must install the AppIndicator development libraries. Run one of the following commands:

    sudo apt-get install libayatana-appindicator3-dev

    OR

    sudo apt-get install appindicator3-0.1 libappindicator3-dev
    dependencies:
      tray_manager: ^0.5.2
  3. Troubleshoot tray_manager issues

    main

    If you use the app_links package, menu click events might not trigger because low versions of app_links block event propagation. Solutions:

    1. Ensure app_links version is ^6.3.3 or higher.
    2. Alternatively, use the protocol_handler package instead of app_links.

    GNOME (Linux) visibility

    If the tray icon is not showing in GNOME, you may need to install the AppIndicator extension.

  4. Set up a system tray icon and context menu

    main

    To use the tray, you need to set an icon (using .ico for Windows and .png for other platforms) and define a Menu containing MenuItem objects. Use trayManager.setContextMenu(menu) to apply the menu to the tray icon.

    import 'package:flutter/material.dart' hide MenuItem;
    import 'package:tray_manager/tray_manager.dart';
    
    await trayManager.setIcon(
      Platform.isWindows
        ? 'images/tray_icon.ico'
        : 'images/tray_icon.png',
    );
    
    Menu menu = Menu(
      items: [
        MenuItem(
          key: 'show_window',
          label: 'Show Window',
        ),
        MenuItem.separator(),
        MenuItem(
          key: 'exit_app',
          label: 'Exit App',
        ),
      ],
    );
    await trayManager.setContextMenu(menu);
  5. TrayManager API Reference

    main

    The TrayManager class provides methods to control the system tray icon and its associated context menu across Linux, macOS, and Windows.

    Method           | Description                                | Linux | macOS | Windows
    -----------------|---------------------------------------------|-------|-------|--------
    destroy          | Destroys the tray icon immediately.         | ✔️    | ✔️    | ✔️
    setIcon          | Sets the image associated with this tray icon.| ✔️    | ✔️    | ✔️
    setIconPosition  | Sets the icon position of the tray icon.    | ➖    | ✔️    | ➖
    setToolTip       | Sets the hover text for this tray icon.     | ➖    | ✔️    | ✔️
    setContextMenu   | Sets the context menu for this icon.        | ✔️    | ✔️    | ✔️
    popUpContextMenu | Pops up the context menu of the tray icon.  | ➖    | ✔️    | ✔️
    getBounds        | Returns `Rect` The bounds of this tray icon. | ➖    | ✔️    | ➖
  6. Reference the TrayManager API

    main

    The TrayManager class provides the following methods for controlling the system tray:

    MethodDescriptionLinuxmacOSWindows
    destroy()Immediately destroys the tray icon.✔️✔️✔️
    setIcon(String path)Sets the image associated with the tray icon.✔️✔️✔️
    setIconPosition(int position)Sets the position of the tray icon.➖✔️➖
    setToolTip(String text)Sets the hover text for the tray icon.➖✔️➖
    setContextMenu(Menu menu)Sets the context menu for the icon.✔️✔️✔️
    popUpContextMenu()Pops up the tray icon's context menu.➖✔️➖
    getBounds()Returns a Rect representing the tray icon's boundaries.➖➖✔️
  7. Use the TrayManager singleton to control system tray icons

    main

    The TrayManager class provides a singleton instance, trayManager, to manage the system tray icon, its tooltip, title, and context menu.

    Setting the Icon

    Use setIcon(iconPath, ...) to set the tray icon.

    Important Sandbox Note (Linux): If your app is running in a sandbox like Flatpak or Snap, iconPath should be the name of the icon as specified in your app's manifest file, without the path or file extension (e.g., org.example.app).

    macOS Specifics: You can use isTemplate, iconPosition, and iconSize to customize the icon appearance on macOS.

    Managing the Context Menu

    Use setContextMenu(Menu menu) to attach a menu to the tray icon. You can also manually trigger the menu using popUpContextMenu().

    import 'package:tray_manager/tray_manager.dart';
    
    // Set the icon
    await trayManager.setIcon('assets/images/tray_icon.png');
    
    // Set a tooltip (must be called after setIcon)
    await trayManager.setToolTip('My App Tooltip');
    
    // Set a context menu
    await trayManager.setContextMenu(myMenu);
  8. Listen to tray icon events with TrayListener

    main

    To respond to user interactions with the tray icon (such as clicks or menu item selections), implement a TrayListener and register it with trayManager.addListener(listener).

    Commonly handled events include:

    • onTrayIconMouseDown / onTrayIconMouseUp
    • onTrayIconRightMouseDown / onTrayIconRightMouseUp
    • onTrayMenuItemClick (triggered when a menu item is selected)

    Always remember to call trayManager.removeListener(listener) when the listener is no longer needed to prevent memory leaks.

    class MyTrayListener extends TrayListener {
      @override
      void onTrayMenuItemClick(MenuItem menuItem) {
        print('Clicked: ${menuItem.label}');
      }
    }
    
    // Usage
    final myListener = MyTrayListener();
    trayManager.addListener(myListener);
  9. Get the bounds of the tray icon

    main

    You can retrieve the screen coordinates and dimensions of the tray icon using getBounds(). This returns a Rect? containing the x, y, width, and height of the icon, adjusted for the device's pixel ratio. This is useful for positioning overlay widgets near the tray icon.

    final Rect? bounds = await trayManager.getBounds();
    if (bounds != null) {
      print('Icon is at: ${bounds.toString()}');
    }