Search code examples
flutterwindowsdartkeyboard-shortcuts

How to make the alt+left arrow go back in flutter?


I want the page that I am currently in to be poped when I press Alt+backArrow on the keyboard on the Windows platform.

Like in web browsers or on Steam.


Solution

  • To achieve this behavior, you can wrap your page content or any specific widget with a KeyboardListener widget and configure it to listen for the Alt key combined with the left arrow key (Alt + BackArrow). Here's an example:

    KeyboardListener(
      autofocus: true, // Ensures the widget is ready to listen to keyboard events without requiring focus
      focusNode: FocusNode(), // A focus node to manage focus on this widget
      onKeyEvent: (event) {
        // Check if the Alt key is pressed (HardwareKeyboard.instance.isAltPressed) and the left arrow key is pressed (event.logicalKey == LogicalKeyboardKey.arrowLeft) at the same time, and if it’s a key down event (event is KeyDownEvent)
        if (HardwareKeyboard.instance.isAltPressed &&
            event.logicalKey == LogicalKeyboardKey.arrowLeft &&
            event is KeyDownEvent) {
          Navigator.of(context).pop(); // Pop the current page from the navigation stack
        }
      },
      child: MyWidget(), // Replace 'MyWidget' with your actual page or widget content
    )