BambinoUA
BambinoUA

Reputation: 7100

RawKeyboardListener not fired any event in Flutter web

Here it is simple code inside some widget. The RawKeyboardListener's onKey is not triggered! So the question why? Is it a bug?

Container(
  child: StreamProvider<Item>.value(
    value: stream
    child: Consumer<Item>(
      builder: (_, item, __) {
        return RawKeyboardListener(
          focusNode: focusNode,
          onKey: (event) {
            print(event); // NOT PRINTED!!
          }
          child: TextField(
            controller: controller,
            ...
          ),
        );
      }
    ),
  ),
),

P.S. Flutter is 1.17.0-3.2pre, Dart is 2.8.0-dev.20.10

Upvotes: 6

Views: 2865

Answers (2)

BambinoUA
BambinoUA

Reputation: 7100

Finally, I figured out why keys (and Enter especially) are not catched by RawKeyboardListener. It is required to add onChange callback (for catching keyboard events) and an empty onEditingComplete callback (for catching Enter key).

RawKeyboardListener(
  focusNode: focusNode,
  onKey: (event) {
    if (event.isKeyPressed(LogicalKeyboardKey.enter) {
      print('enter key pressed'); // <--- works!
    } else {
      print('key ${event.logicalKey} pressed');
    }
  }
  child: TextField(
    controller: controller,
    onChange: (value) { /* handle text change*/}
    onEditingComplete: () { /* this is required to catch Enter key */ }
  ),
)

Upvotes: 1

BananaNeil
BananaNeil

Reputation: 10762

I think you need to add this line to the top of your builder method:

FocusScope.of(context).requestFocus(focusNode);

Your code should look like this:

Container(
  child: StreamProvider<Item>.value(
    value: stream
    child: Consumer<Item>(
      builder: (_, item, __) {
        FocusScope.of(context).requestFocus(focusNode); // Add this line

        return RawKeyboardListener(
          focusNode: focusNode,
          onKey: (event) {
            print(event); // NOT PRINTED!!
          }
          child: TextField(
            controller: controller,
            ...
          ),
        );
      }
    ),
  ),
),

Upvotes: 5

Related Questions