I'm trying to detect key presses like "Enter", "Delete" and "Backspace" within flutter. My issue with using a RawKeyboardListener
is that it takes focus away from any child widgets.
For example
RawKeyboardListener(
focusNode: _focusNode,
onKey: handleKey,
child: TextField()
)
This makes it impossible to detect both key presses and use the Textfield
at the same time.
Does anyone have a alternative way for detecting key presses.
Thanks
You can use the following from dart_html:
window.onKeyPress.listen((KeyboardEvent e) {
print(e.charCode.toString() + " " + new String.fromCharCode(e.charCode));
});
You can use dart:ui
and set method window.onKeyData
in initState
in a stateful widget
Be careful with that method as if you have any focusable nodes on the screen you will need to pass events to them too, otherwise, for example, TextField will not work.
@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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With