RawKeyDownEvent not triggered for Flutter Web

Issue

I have implemented RawKeyboardListener in my Flutter app and it works flawlessly on Android and on Chrome when debugging. When Firebase hosted, it is not catching any keypress event.

RawKeyboardListener(
      autofocus: true,
      focusNode: focusNode,
      onKey: (RawKeyEvent event) {
        if (event.runtimeType.toString()  'RawKeyDownEvent') {
            //some action
        }
      },
      child: Padding(
        padding: const EdgeInsets.fromLTRB(0, 10.0, 0, 10.0),
        child: Text(keyedText,
            style: TextStyle(color: Colors.black, fontSize: 40.0)),
      ),
    )

I researched and found I can look for RawKeyEventDataWeb. Changed the code for RawKeyEventDataWeb instead of RawKeyDownEvent, but the problem is RawKeyEventDataWeb listened to both up and down key events and hence anything typed comes twice.

How do I resolve this?

Solution

I do not know the “right” way to solve this. But here is a workaround I figured. Any pair of ‘Up’ and ‘Down’ key events are triggered within 200 milliseconds. So I used this fact to ignore any event that is within 200 or so milliseconds. Not the best solution, but works.

RawKeyboardListener(
      autofocus: true,
      focusNode: focusNode,
      onKey: (RawKeyEvent event) {
        int currentKeyPressTime  DateTime.now().millisecondsSinceEpoch;
        if (event.runtimeType.toString()  'RawKeyDownEvent' ||
            event.data is RawKeyEventDataWeb &&
                currentKeyPressTime > lastKeyPressTime + 200) {
          lastKeyPressTime  currentKeyPressTime;
          // some action
        }
      },
      child: Padding(
        padding: const EdgeInsets.fromLTRB(0, 10.0, 0, 10.0),
        child: Text(keyedText,
            style: TextStyle(color: Colors.black, fontSize: 40.0)),
      ),
    ),

Just remember to initialize lastKeyPressTime sometime before.

Answered By – sivag1

Leave a Comment