Flutter系统热键管理插件hotkey_system的使用

Flutter系统热键管理插件hotkey_system的使用


HotkeySystem

该插件允许Flutter桌面应用程序定义系统级或应用内全局快捷键。


平台支持

Linux macOS Windows
✔️ ✔️ ✔️

快速开始

安装

pubspec.yaml文件中添加以下依赖项:

dependencies:
  hotkey_system: ^0.0.9

或者从Git仓库安装:

dependencies:
  hotkey_system:
    git:
      url: https://github.com/suysoftware/hotkey_system.git
      ref: main

Linux 需求

需要安装 keybinder-3.0

sudo apt-get install keybinder-3.0

使用

首先,确保初始化WidgetsFlutterBinding

import 'package:hotkey_system/hotkey_system.dart';

void main() async {
  // 必须添加此行
  WidgetsFlutterBinding.ensureInitialized();
  // 对于热重载,需要调用 unregisterAll()
  await hotKeySystem.unregisterAll();

  runApp(MyApp());
}

注册/注销系统级或应用内全局快捷键:

// ⌥ + Q
HotKey _hotKey = HotKey(
  KeyCode.keyQ,
  modifiers: [KeyModifier.alt],
  // 设置快捷键范围(默认为HotKeyScope.system)
  scope: HotKeyScope.inapp, // 设置为应用内全局快捷键
);

await hotKeySystem.register(
  _hotKey,
  keyDownHandler: (hotKey) {
    print('onKeyDown+${hotKey.toJson()}');
  },
  // 仅适用于macOS
  keyUpHandler: (hotKey) {
    print('onKeyUp+${hotKey.toJson()}');
  },
);

await hotKeySystem.unregister(_hotKey);

await hotKeySystem.unregisterAll();

使用 HotKeyRecorder 小部件帮助你记录快捷键:

HotKeyRecorder(
  onHotKeyRecorded: (hotKey) {
    _hotKey = hotKey;
    setState(() {});
  },
),

使用 HotKeyRecorder 小部件并带有初始快捷键:

HotKeyRecorder(
  onHotKeyRecorded: (hotKey) {
    _hotKey = hotKey;
    setState(() {});
  },
  initialHotKey: HotKey.fromJson({
    "keyCode": "keyR",
    "modifiers": ["meta"],
    "identifier": "fdf8484b-5249-42bb-b473-d99bfb7bb3e8",
    "scope": "system"
  }),
),

注册时使用标识符:

// ⌥ + Q
HotKey _hotKey = HotKey(
  KeyCode.keyQ,
  modifiers: [KeyModifier.alt],
  identifier: "examleidentifier",
  // 设置快捷键范围(默认为HotKeyScope.system)
  scope: HotKeyScope.inapp, // 设置为应用内全局快捷键
);

await hotKeySystem.register(
  _hotKey,
  keyDownHandler: (hotKey) {
    print('onKeyDown+${hotKey.toJson()}');
  },
  // 仅适用于macOS
  keyUpHandler: (hotKey) {
    print('onKeyUp+${hotKey.toJson()}');
  },
);

HotKey.fromJson 的使用:

HotKey _hotKey = HotKey.fromJson({
  "keyCode": "keyR",
  "modifiers": ["meta"],
  "identifier": "fdf8484b-5249-42bb-b473-d99bfb7bb3e8",
  "scope": "system"
});

await hotKeySystem.register(
  _hotKey,
  keyDownHandler: (hotKey) {
    print('onKeyDown+${hotKey.toJson()}');
  },
  // 仅适用于macOS
  keyUpHandler: (hotKey) {
    print('onKeyUp+${hotKey.toJson()}');
  },
);

HotKeyVirtualView 的使用:

return HotKeyVirtualView(HotKey.fromJson({
  "keyCode": "keyR",
  "modifiers": ["meta"],
  "identifier": "fdf8484b-5249-42bb-b473-d99bfb7bb3e8",
  "scope": "system"
}));

包解析器:

// 将字符串解析为 KeyModifier
KeyModifier modifier = KeyModifierParser.parse("shift");

// 从 KeyModifier 获取 ModifierKey
ModifierKey modKey = modifier.modifierKey;

// 从 KeyModifier 获取 LogicalKeyboardKeys
List<LogicalKeyboardKey> keys = modifier.logicalKeys;

// 获取 KeyModifier 的标签
String label = modifier.keyLabel;

// 将 LogicalKeyboardKey 转换为 KeyCode
KeyCode keyCode = KeyCodeParser.fromLogicalKey(LogicalKeyboardKey.keyA);

// 从 KeyCode 获取 LogicalKeyboardKey
LogicalKeyboardKey logicalKey = keyCode.logicalKey;

// 将字符串解析为 KeyCode
KeyCode parsedKeyCode = KeyCodeParser.parse("keyA");

// 获取 KeyCode 的标签
String keyLabel = keyCode.keyLabel;

修饰符:

KeyModifier.alt // macOS: option & windows: alt
KeyModifier.shift // macOS: shift & windows: shift
KeyModifier.meta // macOS: cmd & windows: windows key
KeyModifier.control // macOS: control & windows: control

// 控制键
String controlKeyLabel = KeyCode.control.keyLabel; // macOS 返回 '⌃', Windows 返回 'Ctrl'
// 上档键
String shiftKeyLabel = KeyCode.shift.keyLabel; // 返回 '⇧'
// 选项键
String altKeyLabel = KeyCode.alt.keyLabel; // macOS 返回 '⌥', Windows 返回 'Alt'
// 命令键
String metaKeyLabel = KeyCode.meta.keyLabel; // macOS 返回 '⌘', Windows 返回 '⊞'

HotKey 对象:

enum HotKeyScope {
  system,
  inapp,
}

class HotKey {
  HotKey(
    this.keyCode, {
    this.modifiers,
    String? identifier,
    HotKeyScope? scope,
  }) {
    if (identifier != null) this.identifier = identifier;
    if (scope != null) this.scope = scope;
  }

  factory HotKey.fromJson(Map<String, dynamic> json) {
    return HotKey(
      KeyCodeParser.parse(json['keyCode']),
      modifiers: List<String>.from(json['modifiers'])
          .map((e) => KeyModifierParser.parse(e))
          .toList(),
      identifier: json['identifier'],
      scope: HotKeyScope.values.firstWhere(
        (e) => e.name == json['scope'],
        orElse: () => HotKeyScope.system,
      ),
    );
  }

  KeyCode keyCode;
  List<KeyModifier>? modifiers;
  String identifier = DateTime.now().millisecondsSinceEpoch.toString();
  HotKeyScope scope = HotKeyScope.system;

  Map<String, dynamic> toJson() {
    return {
      'keyCode': keyCode.name,
      'modifiers': modifiers?.map((e) => e.name).toList() ?? [],
      'identifier': identifier,
      'scope': scope.name.toString(),
    };
  }

  [@override](/user/override)
  String toString() {
    return '${modifiers?.map((e) => e.keyLabel).join('')}${keyCode.keyLabel}';
  }
}

使用案例

请参阅该插件的示例应用以获取完整示例:

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:hotkey_system/hotkey_system.dart';
import 'package:hotkey_system_example/pages/home.dart';

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

  await hotKeySystem.unregisterAll();

  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Color(0xff416ff4),
        canvasColor: Colors.white,
        scaffoldBackgroundColor: Color(0xffF7F9FB),
        dividerColor: Colors.grey.withOpacity(0.3),
      ),
      builder: BotToastInit(),
      navigatorObservers: [BotToastNavigatorObserver()],
      home: HomePage(),
    );
  }
}

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

1 回复

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


当然,以下是一个关于如何使用 hotkey_system 插件来管理 Flutter 应用中的系统热键的示例代码。hotkey_system 插件允许你监听和处理全局热键事件。

首先,确保你已经在 pubspec.yaml 文件中添加了 hotkey_system 依赖:

dependencies:
  flutter:
    sdk: flutter
  hotkey_system: ^最新版本号 # 请替换为最新版本号

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

以下是一个简单的 Flutter 应用示例,展示了如何使用 hotkey_system 插件:

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final HotkeySystem _hotkeySystem = HotkeySystem();

  @override
  void initState() {
    super.initState();

    // 注册一个热键组合,例如 Ctrl + Shift + A
    _hotkeySystem.registerHotkey(
      LogicalKeyboardKey.controlLeft,
      LogicalKeyboardKey.shiftLeft,
      LogicalKeyboardKey.keyA,
      onHotkeyPressed: () {
        print('Ctrl + Shift + A 被按下');
        // 在这里添加你的热键处理逻辑
      },
    );

    // 监听热键事件
    _hotkeySystem.hotkeyEvent.listen((event) {
      print('热键事件: $event');
    });
  }

  @override
  void dispose() {
    // 注销热键并停止监听事件
    _hotkeySystem.unregisterAllHotkeys();
    _hotkeySystem.hotkeyEvent.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Hotkey System Demo'),
        ),
        body: Center(
          child: Text('按下 Ctrl + Shift + A 来触发热键事件'),
        ),
      ),
    );
  }
}

代码解释:

  1. 依赖导入:首先,导入 hotkey_system 包。
  2. 创建应用:定义一个 MyApp 类,并继承 StatefulWidget
  3. 状态管理:在 _MyAppState 类中,创建一个 HotkeySystem 实例。
  4. 注册热键:在 initState 方法中,使用 _hotkeySystem.registerHotkey 方法注册一个热键组合(例如 Ctrl + Shift + A)。
  5. 处理热键事件:定义一个 onHotkeyPressed 回调函数来处理热键事件。
  6. 监听热键事件:使用 _hotkeySystem.hotkeyEvent.listen 方法监听所有热键事件。
  7. 注销热键:在 dispose 方法中,使用 _hotkeySystem.unregisterAllHotkeys 方法注销所有已注册的热键,并取消事件监听。

注意事项:

  • 确保你的应用有权限监听全局热键事件(某些平台可能需要特定的权限设置)。
  • 热键注册和监听应在 initStatedispose 中进行,以确保资源正确管理。
  • 在实际开发中,根据需要添加更多的热键和处理逻辑。

这样,你就可以在你的 Flutter 应用中使用 hotkey_system 插件来管理系统热键了。

回到顶部