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

Viewed 464

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.

2 Answers

RawKeyboard is probably what you are looking for

sample:

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

i use this method to detect if ctrl + v or cmd + v is pressed, to get image from clipboard

1

// declare focusNode first
final _fokusTitle = FocusNode();

...

2

Padding(
            padding: const EdgeInsets.all(60),
            // listen key press widget
            child: RawKeyboardListener(
              // add focus node here
              focusNode: _fokusTitle,
              child: Text("halo apa kabar , saya disini"),
              onKey: (x) async {
                // detect if ctrl + v or cmd + v is pressed
                if (x.isControlPressed && x.character == "v" || x.isMetaPressed && x.character == "v") {
                  // you need add some package "pasteboard" , 
                  // if you wan to get image from clipboard, or just replace with some handle
                  final imageBytes = await Pasteboard.image;
                  print(imageBytes?.length);
                }
              },
            ),
          )

...

3

Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  // keyboard listener will catch some key pressed here , if you focused cursor here
                                  child: TextFormField(
                                    focusNode: _fokusTitle,
                                    controller: _controllerTitle,
                                    maxLength: 50,
                                    maxLines: 1,
                                    decoration: InputDecoration(hintText: "mulai ketik sesuatu", labelText: "judul"),
                                  ),
                                ),
Related