Flutter: How can I prevent default behaviour on key press?

1,265

I've faced a similar problem and what to share how I solved it.

To stop the propagation we have to return true from onKey method of a FocusNode in the focus nodes tree. To achieve this I've wrapped my app body with FocusScope and Focus widgets like this:

MaterialApp(
      home: Scaffold(
          body: FocusScope(
              autofocus: true,
              child: Focus(
                  autofocus: true,
                  canRequestFocus: true,
                  onKey: (data, event) {
                    if (event.isKeyPressed(LogicalKeyboardKey.audioVolumeUp)) {
                      print("Volume up");
                      return true;
                    }
                    if (event
                        .isKeyPressed(LogicalKeyboardKey.audioVolumeDown)) {
                      print("Volume down");
                      return true;
                    }
                    return false;
                  },
                  child: Text(text: "Hallochen")))))
Share:
1,265
joseph
Author by

joseph

Updated on December 07, 2022

Comments

  • joseph
    joseph over 1 year

    I'm trying to intercept when a user presses the volume buttons to perform a specific action and prevent the default behaviour (volume changes).

    This is the code I have so far:

    RawKeyboard.instance.addListener(_keyboardListener);
    
    void _keyboardListener(RawKeyEvent e) {
      if(e.runtimeType == RawKeyUpEvent) {
        RawKeyEventDataAndroid eA = e.data;
        if(eA.keyCode == 24) { //volume up key
          _goNextPage();
        }
        if(eA.keyCode == 25) { //volume down key
          _goPrevPage();
        }
      }
    }
    

    How would I go about preventing the volume from changing (and stopping the volume slider from appearing at the top)?

    A Javascript analogous would be calling event.preventDefault() on the key event.

    This seems to be a rather trivial matter, but I haven't been able to find any answers in the docs.

    Thanks.