Flutter RawKeyboardListener listening twice?

The onKey callback is triggered for both key down and key up events. That's why it appears to be called twice for a single key press.

When handling the events, I prefer using is rather than accessing the runtime type:

onKey: (RawKeyEvent event) {
  if (event is RawKeyDownEvent) {
    // handle key down
  } else if (event is RawKeyUpEvent) {
    // handle key up
  }
},

Your callback is getting called for both keydown and keyup events with instances of following classes:

  • RawKeyDownEvent
  • RawKeyUpEvent

You can pass the whole object to handleKey, and filter based on runtime type of object. for example

  handleKey(RawKeyEvent key) {
    print("Event runtimeType is ${key.runtimeType}");
    if(key.runtimeType.toString() == 'RawKeyDownEvent'){
        RawKeyEventDataAndroid data = key.data as RawKeyEventDataAndroid;
        String _keyCode;
        _keyCode = data.keyCode.toString(); //keycode of key event (66 is return)

        print("why does this run twice $_keyCode");
    }
  }

  _buildTextComposer() {
      TextField _textField = new TextField(
          controller: _controller,
          onSubmitted: _handleSubmitted,
      );

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

      return new RawKeyboardListener(
          focusNode: _textNode,
          onKey: handleKey,
          child: _textField
      );
  }

If this still does not help, check actual runtimeTypes logged from handleKey method, and filter by those.