Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect key presses in flutter without a RawKeyboardListener

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

like image 869
Lachlan Avatar asked Jan 23 '20 02:01

Lachlan


2 Answers

You can use the following from dart_html:

    window.onKeyPress.listen((KeyboardEvent e) {
      print(e.charCode.toString() + " " + new String.fromCharCode(e.charCode));
    });
like image 139
Robin Bozan Avatar answered Nov 17 '22 10:11

Robin Bozan


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();
  }
like image 2
Arenukvern Avatar answered Nov 17 '22 10:11

Arenukvern