| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- import 'dart:async';
- import 'package:flutter/services.dart';
- import 'package:keyboard/plugins/plugin_constant.dart';
- /// 默认键盘切换回调
- typedef DefaultKeyboardChangeListenerCallback =
- void Function(bool isDefaultKeyboard);
- /// 默认键盘改变事件监听器
- class DefaultKeyboardMonitor {
- DefaultKeyboardMonitor._();
- /// 事件通道
- static const EventChannel _eventChannel = EventChannel(
- PluginConstant.flutterDefaultKeyboardEventChannelName,
- );
- /// 监听器列表
- static final List<DefaultKeyboardChangeListenerCallback> _listenerList =
- <DefaultKeyboardChangeListenerCallback>[];
- /// 订阅事件流
- static StreamSubscription? _streamSubscription;
- /// 初始化
- static init() {
- _streamSubscription = _eventChannel.receiveBroadcastStream().listen(
- (dynamic event) {
- bool isDefaultKeyboard = event as bool;
- // 切换事件,true为当前键盘为默认键盘,false为不是默认键盘
- for (var listener in _listenerList) {
- listener(isDefaultKeyboard);
- }
- },
- onError: (dynamic error) {},
- cancelOnError: true,
- );
- }
- /// 解初始化
- static unInit() {
- if (_streamSubscription != null) {
- _streamSubscription!.cancel();
- _streamSubscription = null;
- }
- }
- /// 注册默认键盘改变事件监听器
- static void registerDefaultKeyboardChangeEvent(
- DefaultKeyboardChangeListenerCallback callback,
- ) {
- if (!_listenerList.contains(callback)) {
- _listenerList.add(callback);
- }
- }
- /// 注销默认键盘改变事件监听器
- static void unRegisterDefaultKeyboardChangeEvent(
- DefaultKeyboardChangeListenerCallback callback,
- ) {
- _listenerList.remove(callback);
- }
- }
|