如何在没有 RawKeyboardListener 的情况下检测颤振中的按键
How to detect key presses in flutter without a RawKeyboardListener
我正在尝试检测 flutter 中的 "Enter"、"Delete" 和 "Backspace" 等按键。我使用 RawKeyboardListener
的问题是它会将焦点从任何子小部件上移开。
例如
RawKeyboardListener(
focusNode: _focusNode,
onKey: handleKey,
child: TextField()
)
这使得无法同时检测到两个按键和使用 Textfield
。
有没有人有其他检测按键的方法。
谢谢
您可以使用 dart_html 中的以下内容:
window.onKeyPress.listen((KeyboardEvent e) {
print(e.charCode.toString() + " " + new String.fromCharCode(e.charCode));
});
您可以在有状态小部件initState
中使用 dart:ui
和设置方法 window.onKeyData
小心使用该方法,因为如果屏幕上有任何可聚焦的节点,您也需要将事件传递给它们,否则,例如,TextField 将无法工作。
@override
void initState() {
window.onKeyData = (final keyData) {
if (keyData.logical == LogicalKeyboardKey.escape.keyId) {
widget.onPressed();
return true;
}
/// Let event pass to other focuses if it is not the key we looking for
return false;
};
super.initState();
}
@override
void dispose() {
window.onKeyData = null;
super.dispose();
}
我正在尝试检测 flutter 中的 "Enter"、"Delete" 和 "Backspace" 等按键。我使用 RawKeyboardListener
的问题是它会将焦点从任何子小部件上移开。
例如
RawKeyboardListener(
focusNode: _focusNode,
onKey: handleKey,
child: TextField()
)
这使得无法同时检测到两个按键和使用 Textfield
。
有没有人有其他检测按键的方法。
谢谢
您可以使用 dart_html 中的以下内容:
window.onKeyPress.listen((KeyboardEvent e) {
print(e.charCode.toString() + " " + new String.fromCharCode(e.charCode));
});
您可以在有状态小部件initState
中使用 dart:ui
和设置方法 window.onKeyData
小心使用该方法,因为如果屏幕上有任何可聚焦的节点,您也需要将事件传递给它们,否则,例如,TextField 将无法工作。
@override
void initState() {
window.onKeyData = (final keyData) {
if (keyData.logical == LogicalKeyboardKey.escape.keyId) {
widget.onPressed();
return true;
}
/// Let event pass to other focuses if it is not the key we looking for
return false;
};
super.initState();
}
@override
void dispose() {
window.onKeyData = null;
super.dispose();
}