flutterdartkeystrokectrl

Flutter - actively check if special key (like ctrl) is pressed


Question: How to actively check if a certain (decoration) key is pressed, like CTRL or SHIFT, like:

if (SomeKeyboardRelatedService.isControlPressed()) {...}

background

I'd like to check if a certain (decoration) key is pressed when the user clicks the mouse. We cannot manage to do it actively. Instead, we are using RawKeyboardListener and remember the isControlPressed in onKey event. This way, later in GestureDetector.onTap we can check if isControlPressed is true. The problem is:

  1. It seems nowhere reasonable to maintain the key pressed state on our own, as it violated the single-source-of-truth principle and may cause inconsistency.
  2. It actually IS causing inconsistency, if the user switches away from the app while holding the special key.

We have read relevant docs and searched with several keywords and ended up with no result.


Solution

  • RawKeyboard is probably what you are looking for. Example:

    RawKeyboard.instance.keysPressed.contains(LogicalKeyboardKey.controlLeft)
    

    Note that you need to check for all possible key variants when checking for control keys etc.

    final shiftKeys = [LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight];
    final isShiftPressed = RawKeyboard.instance.keysPressed
        .where((it) => shiftKeys.contains(it))
        .isNotEmpty;