📚 Encyclopedia

Flutter & Mobile · updated 2026-10-13

Keyboard shortcuts and focus in Flutter

flutterkeyboardshortcutsfocuscallbackshortcutsflameweb

Flutter has several ways to handle keys, and the wrong one produces handlers that silently stop firing. Researched (2025-2026 Flutter) and battle-tested in Run's level editor, skin editor, and level select screen.

Use CallbackShortcuts for app/editor shortcuts

CallbackShortcuts(
  bindings: {
    SingleActivator(LogicalKeyboardKey.keyZ, control: true): undo,
    SingleActivator(LogicalKeyboardKey.keyZ, control: true, shift: true): redo,
    SingleActivator(LogicalKeyboardKey.keyS, control: true): save,
    SingleActivator(LogicalKeyboardKey.delete): deleteSelected,
  },
  child: Focus(autofocus: true, focusNode: _focusNode, child: Scaffold(...)),
)

Avoid

Do not fire shortcuts while the user types

Bare letter shortcuts (V = select tool) will eat keystrokes in text fields. In Run the check primaryFocus.context.widget is EditableText did not work (verified empirically). What works: dispatch from a Focus.onKeyEvent and bail out when primaryFocus?.context?.findAncestorWidgetOfExactType<EditableText>() != null, returning KeyEventResult.ignored so the field still receives the key.

Global sequence detection without breaking focus (Konami code)

Wrap the screen body in an ancestor Focus(canRequestFocus: false, skipTraversal: true, onKeyEvent: (node, e) { feed(e); return KeyEventResult.ignored; }). Children that ignore a key let it bubble up to this node, so arrow-key navigation between tiles keeps working while the ancestor watches for up up down down left right left right B A. Run uses this to open a cheat-code dialog (and a long-press on a level tile for touch devices).

Platform quirks

Inside a Flame game

Use HasKeyboardHandlerComponents + KeyboardHandler components for gameplay (cannot be mixed with KeyboardEvents on the same game). GameWidget autofocuses and regains focus after overlays close (Flame 1.4+). For rebindable controls, map logical keys to game actions in a small service persisted to prefs (Run: 9 actions, End as a default restart key).

See also

Linked from

Sources: run memory (research-keyboard-input.md, improvement-cycles.md, session-v078-v079.md, MEMORY.md key gotchas)