default_keyboard_monitor.dart 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import 'dart:async';
  2. import 'package:flutter/services.dart';
  3. import 'package:keyboard/plugins/plugin_constant.dart';
  4. /// 默认键盘切换回调
  5. typedef DefaultKeyboardChangeListenerCallback =
  6. void Function(bool isDefaultKeyboard);
  7. /// 默认键盘改变事件监听器
  8. class DefaultKeyboardMonitor {
  9. DefaultKeyboardMonitor._();
  10. /// 事件通道
  11. static const EventChannel _eventChannel = EventChannel(
  12. PluginConstant.flutterDefaultKeyboardEventChannelName,
  13. );
  14. /// 监听器列表
  15. static final List<DefaultKeyboardChangeListenerCallback> _listenerList =
  16. <DefaultKeyboardChangeListenerCallback>[];
  17. /// 订阅事件流
  18. static StreamSubscription? _streamSubscription;
  19. /// 初始化
  20. static init() {
  21. _streamSubscription = _eventChannel.receiveBroadcastStream().listen(
  22. (dynamic event) {
  23. bool isDefaultKeyboard = event as bool;
  24. // 切换事件,true为当前键盘为默认键盘,false为不是默认键盘
  25. for (var listener in _listenerList) {
  26. listener(isDefaultKeyboard);
  27. }
  28. },
  29. onError: (dynamic error) {},
  30. cancelOnError: true,
  31. );
  32. }
  33. /// 解初始化
  34. static unInit() {
  35. if (_streamSubscription != null) {
  36. _streamSubscription!.cancel();
  37. _streamSubscription = null;
  38. }
  39. }
  40. /// 注册默认键盘改变事件监听器
  41. static void registerDefaultKeyboardChangeEvent(
  42. DefaultKeyboardChangeListenerCallback callback,
  43. ) {
  44. if (!_listenerList.contains(callback)) {
  45. _listenerList.add(callback);
  46. }
  47. }
  48. /// 注销默认键盘改变事件监听器
  49. static void unRegisterDefaultKeyboardChangeEvent(
  50. DefaultKeyboardChangeListenerCallback callback,
  51. ) {
  52. _listenerList.remove(callback);
  53. }
  54. }