chatapp3-flutter/lib/shared/tools/sc_keybord_util.dart
2026-04-09 21:32:23 +08:00

64 lines
1.6 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:flutter/cupertino.dart';
class SCKeybordUtil {
static final List<Function(bool)> _lst = [];
static bool _kbVis = false;
static double _kbHt = 0.0;
/// 添加全局键盘监听
static void onChange(Function(bool visible) listener) {
_lst.add(listener);
// 立即通知当前状态
listener(_kbVis);
}
/// 移除监听器
static void removeListener(Function(bool visible) listener) {
_lst.remove(listener);
}
/// 初始化键盘监听必须在MaterialApp外层调用
static void init() {
WidgetsBinding.instance.addObserver(_KbObs());
}
/// 获取当前键盘是否可见
static bool get isVisible => _kbVis;
/// 获取当前键盘高度
static double get height => _kbHt;
/// 隐藏键盘
static void hide(BuildContext context) {
FocusScope.of(context).unfocus();
}
/// 更新键盘状态(内部使用)
static void _updSt(bool visible, double height) {
if (visible != _kbVis || height != _kbHt) {
_kbVis = visible;
_kbHt = height;
// 通知所有监听器
for (final listener in _lst) {
listener(visible);
}
}
}
}
// 键盘状态观察者
class _KbObs extends WidgetsBindingObserver {
@override
void didChangeMetrics() {
final view = WidgetsBinding.instance.platformDispatcher.views.first;
if (view.viewInsets.bottom > 0) {
// 键盘弹出
SCKeybordUtil._updSt(true, view.viewInsets.bottom);
} else {
// 键盘收起
SCKeybordUtil._updSt(false, 0.0);
}
}
}