Skip to content

MenuAnchor menus captures Escape key incorrectly #135334

Closed

Description

@Caffeinix

Steps to reproduce

  1. Create a menu using MenuAnchor.
  2. Add a keyboard event listener to a widget at the root of the page.
  3. Give that widget keyboard focus.
  4. Open the menu, then press escape, either with your mouse within the menu region (behavior A) or outside the menu region (behavior B).

Expected results

Pressing the escape key while a menu is open should close the menu and perform no other action, regardless of where the mouse happens to be when the escape key is pressed. In this way, a menu should act like a modal overlay. For consistency with native menus, the entire menu hierarchy should be closed, but simply closing the most recently opened submenu would be okay too.

Actual results

Behavior A: If the mouse cursor happens to be within the bounds of the menu when the escape key is pressed [edit: actually it seems to be if a menu item is selected, regardless of whether the mouse is still inside the menu], the menu is closed as expected. However, the escape key event is not captured, so the key listener on the root widget also fires. Given the observed behavior, I suspect it might not fire if the bounding rectangle of that widget does not contain the mouse cursor, but I haven't tested that.

Behavior B: If the mouse cursor is not within the bounds of the menu when the escape key is pressed, the menu remains open, and the key listener on the root widget fires instead.

Code sample

Here's a modified version of the `MenuAnchor` API example where an escape key handler is added to the red background container and it's given keyboard focus when the app is loaded. Click on the menu button to show the menu, and then press the escape key. If your mouse is over the menu when you press the key, the menu will be closed. Otherwise it will not. In both cases, the container's escape key handler will be invoked.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// Flutter code sample for [MenuAnchor].

void main() => runApp(const MenuApp());

/// An enhanced enum to define the available menus and their shortcuts.
///
/// Using an enum for menu definition is not required, but this illustrates how
/// they could be used for simple menu systems.
enum MenuEntry {
  about('About'),
  showMessage(
      'Show Message', SingleActivator(LogicalKeyboardKey.keyS, control: true)),
  hideMessage(
      'Hide Message', SingleActivator(LogicalKeyboardKey.keyS, control: true)),
  colorMenu('Color Menu'),
  colorRed('Red Background',
      SingleActivator(LogicalKeyboardKey.keyR, control: true)),
  colorGreen('Green Background',
      SingleActivator(LogicalKeyboardKey.keyG, control: true)),
  colorBlue('Blue Background',
      SingleActivator(LogicalKeyboardKey.keyB, control: true));

  const MenuEntry(this.label, [this.shortcut]);
  final String label;
  final MenuSerializableShortcut? shortcut;
}

class MyCascadingMenu extends StatefulWidget {
  const MyCascadingMenu({super.key, required this.message});

  final String message;

  @override
  State<MyCascadingMenu> createState() => _MyCascadingMenuState();
}

class _MyCascadingMenuState extends State<MyCascadingMenu> {
  MenuEntry? _lastSelection;
  final FocusNode _buttonFocusNode = FocusNode(debugLabel: 'Menu Button');
  final FocusNode _containerFocusNode = FocusNode(debugLabel: 'Container');
  ShortcutRegistryEntry? _shortcutsEntry;

  Color get backgroundColor => _backgroundColor;
  Color _backgroundColor = Colors.red;
  set backgroundColor(Color value) {
    if (_backgroundColor != value) {
      setState(() {
        _backgroundColor = value;
      });
    }
  }

  bool get showingMessage => _showingMessage;
  bool _showingMessage = false;
  set showingMessage(bool value) {
    if (_showingMessage != value) {
      setState(() {
        _showingMessage = value;
      });
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // Dispose of any previously registered shortcuts, since they are about to
    // be replaced.
    _shortcutsEntry?.dispose();
    // Collect the shortcuts from the different menu selections so that they can
    // be registered to apply to the entire app. Menus don't register their
    // shortcuts, they only display the shortcut hint text.
    final Map<ShortcutActivator, Intent> shortcuts =
        <ShortcutActivator, Intent>{
      for (final MenuEntry item in MenuEntry.values)
        if (item.shortcut != null)
          item.shortcut!: VoidCallbackIntent(() => _activate(item)),
    };
    // Register the shortcuts with the ShortcutRegistry so that they are
    // available to the entire application.
    _shortcutsEntry = ShortcutRegistry.of(context).addAll(shortcuts);
  }

  @override
  void initState() {
    super.initState();
    _containerFocusNode.requestFocus();
  }
  
  @override
  void dispose() {
    _shortcutsEntry?.dispose();
    _buttonFocusNode.dispose();
    _containerFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        MenuAnchor(
          childFocusNode: _buttonFocusNode,
          menuChildren: <Widget>[
            MenuItemButton(
              child: Text(MenuEntry.about.label),
              onPressed: () => _activate(MenuEntry.about),
            ),
            if (_showingMessage)
              MenuItemButton(
                onPressed: () => _activate(MenuEntry.hideMessage),
                shortcut: MenuEntry.hideMessage.shortcut,
                child: Text(MenuEntry.hideMessage.label),
              ),
            if (!_showingMessage)
              MenuItemButton(
                onPressed: () => _activate(MenuEntry.showMessage),
                shortcut: MenuEntry.showMessage.shortcut,
                child: Text(MenuEntry.showMessage.label),
              ),
            SubmenuButton(
              menuChildren: <Widget>[
                MenuItemButton(
                  onPressed: () => _activate(MenuEntry.colorRed),
                  shortcut: MenuEntry.colorRed.shortcut,
                  child: Text(MenuEntry.colorRed.label),
                ),
                MenuItemButton(
                  onPressed: () => _activate(MenuEntry.colorGreen),
                  shortcut: MenuEntry.colorGreen.shortcut,
                  child: Text(MenuEntry.colorGreen.label),
                ),
                MenuItemButton(
                  onPressed: () => _activate(MenuEntry.colorBlue),
                  shortcut: MenuEntry.colorBlue.shortcut,
                  child: Text(MenuEntry.colorBlue.label),
                ),
              ],
              child: const Text('Background Color'),
            ),
          ],
          builder:
              (BuildContext context, MenuController controller, Widget? child) {
            return TextButton(
              focusNode: _buttonFocusNode,
              onPressed: () {
                if (controller.isOpen) {
                  controller.close();
                } else {
                  controller.open();
                }
              },
              child: const Text('OPEN MENU'),
            );
          },
        ),
        Expanded(
          child: KeyboardListener(
            focusNode: _containerFocusNode,
            onKeyEvent: (event) {
              if (event.logicalKey == LogicalKeyboardKey.escape) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('Escape key handler triggered'),
                    duration: Duration(seconds: 1),
                  ),
                );
              }
            },
            child: Container(
              alignment: Alignment.center,
              color: backgroundColor,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(12.0),
                    child: Text(
                      showingMessage ? widget.message : '',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                  ),
                  Text(_lastSelection != null
                      ? 'Last Selected: ${_lastSelection!.label}'
                      : ''),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  void _activate(MenuEntry selection) {
    setState(() {
      _lastSelection = selection;
    });

    switch (selection) {
      case MenuEntry.about:
        showAboutDialog(
          context: context,
          applicationName: 'MenuBar Sample',
          applicationVersion: '1.0.0',
        );
      case MenuEntry.hideMessage:
      case MenuEntry.showMessage:
        showingMessage = !showingMessage;
      case MenuEntry.colorMenu:
        break;
      case MenuEntry.colorRed:
        backgroundColor = Colors.red;
      case MenuEntry.colorGreen:
        backgroundColor = Colors.green;
      case MenuEntry.colorBlue:
        backgroundColor = Colors.blue;
    }
  }
}

class MenuApp extends StatelessWidget {
  const MenuApp({super.key});

  static const String kMessage = '"Talk less. Smile more." - A. Burr';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(useMaterial3: true),
      home: const Scaffold(body: MyCascadingMenu(message: kMessage)),
    );
  }
}

Screenshots or Video

Screenshots / Video demonstration
cast.1.webm

Logs

Logs
[Paste your logs here]

Flutter Doctor output

Doctor output
[Paste your output here]

Activity

  1. added
    in triagePresently being triaged by the triage team
    on Sep 25, 2023
  2. huycozy commented on Sep 25, 2023

    @huycozy
    Member

    Thanks for the report. Reproduced this issue on the latest Flutter channels. But I will update the issue title because it still works in case the mouse is in the menu region.

    flutter doctor -v (stable and master)
    [✓] Flutter (Channel stable, 3.13.5, on macOS 13.5 22G74 darwin-x64, locale en-VN)
        • Flutter version 3.13.5 on channel stable at /Users/huynq/Documents/GitHub/flutter
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 12fccda598 (5 days ago), 2023-09-19 13:56:11 -0700
        • Engine revision bd986c5ed2
        • Dart version 3.1.2
        • DevTools version 2.25.0
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
        • Android SDK at /Users/huynq/Library/Android/sdk
        • Platform android-34, build-tools 32.0.0
        • ANDROID_HOME = /Users/huynq/Library/Android/sdk
        • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 14.3)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Build 14E222b
        • CocoaPods version 1.11.3
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2022.2)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
    
    [✓] VS Code (version 1.82.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.72.0
    
    [✓] Connected device (2 available)
        • macOS (desktop) • macos  • darwin-x64     • macOS 13.5 22G74 darwin-x64
        • Chrome (web)    • chrome • web-javascript • Google Chrome 117.0.5938.62
    
    [✓] Network resources
        • All expected network resources are available.
    
    • No issues found!
    [!] Flutter (Channel master, 3.15.0-7.0.pre.2, on macOS 13.5 22G74 darwin-x64, locale en-VN)
        • Flutter version 3.15.0-7.0.pre.2 on channel master at /Users/huynq/Documents/GitHub/flutter_master
        ! Warning: `flutter` on your path resolves to /Users/huynq/Documents/GitHub/flutter/bin/flutter, which is not inside your current Flutter SDK checkout at /Users/huynq/Documents/GitHub/flutter_master.
          Consider adding /Users/huynq/Documents/GitHub/flutter_master/bin to the front of your path.
        ! Warning: `dart` on your path resolves to /Users/huynq/Documents/GitHub/flutter/bin/dart, which is not inside your current Flutter SDK checkout at /Users/huynq/Documents/GitHub/flutter_master.
          Consider adding /Users/huynq/Documents/GitHub/flutter_master/bin to the front of your path.
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 2f56288a4e (2 hours ago), 2023-09-24 18:49:07 -0700
        • Engine revision 2daf5e7bb2
        • Dart version 3.2.0 (build 3.2.0-191.0.dev)
        • DevTools version 2.28.0-dev.12
        • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades.
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
        • Android SDK at /Users/huynq/Library/Android/sdk
        • Platform android-34, build-tools 32.0.0
        • ANDROID_HOME = /Users/huynq/Library/Android/sdk
        • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
        • All Android licenses accepted.
    
    [✓] Xcode - develop for iOS and macOS (Xcode 14.3)
        • Xcode at /Applications/Xcode.app/Contents/Developer
        • Build 14E222b
        • CocoaPods version 1.11.3
    
    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
    
    [✓] Android Studio (version 2022.2)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
          🔨 https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
    
    [✓] VS Code (version 1.82.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.72.0
    
    [✓] Connected device (2 available)
        • macOS (desktop) • macos  • darwin-x64     • macOS 13.5 22G74 darwin-x64
        • Chrome (web)    • chrome • web-javascript • Google Chrome 117.0.5938.62
    
    [✓] Network resources
        • All expected network resources are available.
    
    ! Doctor found issues in 1 category.
  3. added
    frameworkflutter/packages/flutter repository. See also f: labels.
    p: material_uimaterial_ui package in flutter/packages
    a: mouseIssues related to using a mouse or mouse support
    has reproducible stepsThe issue has been confirmed reproducible and is ready to work on
    team-designOwned by Design Languages team
    and removed
    in triagePresently being triaged by the triage team
    on Sep 25, 2023
  4. changed the title [-]MenuAnchor menus do not capture escape key presses[/-] [+]MenuAnchor menus captures Escape key incorrectly[/+] on Sep 25, 2023
  5. added
    P2Important issues not at the top of the work list
    triaged-designTriaged by Design Languages team
    on Sep 27, 2023
  6. gspencergoog commented on Oct 9, 2023

    @gspencergoog
    Contributor

    Part of the issue here is that the sample uses KeyboardListener, which is exactly that, a listener for key events. If you switch that to a CallbackShortcuts widget, then the escape button doesn't trigger the snackbar if the menu handles it.

    Which is not to say that there isn't an issue here. The remaining issue is that the handling of the escape key for the menu doesn't happen high enough in the widget hierarchy, so unless a menu item is focused (which happens on hover for menu items), it won't see the escape key and dismiss the menu.

    Updated sample using `CallbackShortcuts`
    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    /// Flutter code sample for [MenuAnchor].
    
    void main() => runApp(const MenuApp());
    
    /// An enhanced enum to define the available menus and their shortcuts.
    ///
    /// Using an enum for menu definition is not required, but this illustrates how
    /// they could be used for simple menu systems.
    enum MenuEntry {
      about('About'),
      showMessage('Show Message', SingleActivator(LogicalKeyboardKey.keyS, control: true)),
      hideMessage('Hide Message', SingleActivator(LogicalKeyboardKey.keyS, control: true)),
      colorMenu('Color Menu'),
      colorRed('Red Background', SingleActivator(LogicalKeyboardKey.keyR, control: true)),
      colorGreen('Green Background', SingleActivator(LogicalKeyboardKey.keyG, control: true)),
      colorBlue('Blue Background', SingleActivator(LogicalKeyboardKey.keyB, control: true));
    
      const MenuEntry(this.label, [this.shortcut]);
      final String label;
      final MenuSerializableShortcut? shortcut;
    }
    
    class MyCascadingMenu extends StatefulWidget {
      const MyCascadingMenu({super.key, required this.message});
    
      final String message;
    
      @override
      State<MyCascadingMenu> createState() => _MyCascadingMenuState();
    }
    
    class _MyCascadingMenuState extends State<MyCascadingMenu> {
      MenuEntry? _lastSelection;
      final FocusNode _buttonFocusNode = FocusNode(debugLabel: 'Menu Button');
      final FocusNode _containerFocusNode = FocusNode(debugLabel: 'Container');
      ShortcutRegistryEntry? _shortcutsEntry;
    
      Color get backgroundColor => _backgroundColor;
      Color _backgroundColor = Colors.red;
      set backgroundColor(Color value) {
        if (_backgroundColor != value) {
          setState(() {
            _backgroundColor = value;
          });
        }
      }
    
      bool get showingMessage => _showingMessage;
      bool _showingMessage = false;
      set showingMessage(bool value) {
        if (_showingMessage != value) {
          setState(() {
            _showingMessage = value;
          });
        }
      }
    
      @override
      void didChangeDependencies() {
        super.didChangeDependencies();
        // Dispose of any previously registered shortcuts, since they are about to
        // be replaced.
        _shortcutsEntry?.dispose();
        // Collect the shortcuts from the different menu selections so that they can
        // be registered to apply to the entire app. Menus don't register their
        // shortcuts, they only display the shortcut hint text.
        final Map<ShortcutActivator, Intent> shortcuts = <ShortcutActivator, Intent>{
          for (final MenuEntry item in MenuEntry.values)
            if (item.shortcut != null) item.shortcut!: VoidCallbackIntent(() => _activate(item)),
        };
        // Register the shortcuts with the ShortcutRegistry so that they are
        // available to the entire application.
        _shortcutsEntry = ShortcutRegistry.of(context).addAll(shortcuts);
      }
    
      @override
      void initState() {
        super.initState();
        _containerFocusNode.requestFocus();
      }
    
      @override
      void dispose() {
        _shortcutsEntry?.dispose();
        _buttonFocusNode.dispose();
        _containerFocusNode.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            MenuAnchor(
              childFocusNode: _buttonFocusNode,
              menuChildren: <Widget>[
                MenuItemButton(
                  child: Text(MenuEntry.about.label),
                  onPressed: () => _activate(MenuEntry.about),
                ),
                if (_showingMessage)
                  MenuItemButton(
                    onPressed: () => _activate(MenuEntry.hideMessage),
                    shortcut: MenuEntry.hideMessage.shortcut,
                    child: Text(MenuEntry.hideMessage.label),
                  ),
                if (!_showingMessage)
                  MenuItemButton(
                    onPressed: () => _activate(MenuEntry.showMessage),
                    shortcut: MenuEntry.showMessage.shortcut,
                    child: Text(MenuEntry.showMessage.label),
                  ),
                SubmenuButton(
                  menuChildren: <Widget>[
                    MenuItemButton(
                      onPressed: () => _activate(MenuEntry.colorRed),
                      shortcut: MenuEntry.colorRed.shortcut,
                      child: Text(MenuEntry.colorRed.label),
                    ),
                    MenuItemButton(
                      onPressed: () => _activate(MenuEntry.colorGreen),
                      shortcut: MenuEntry.colorGreen.shortcut,
                      child: Text(MenuEntry.colorGreen.label),
                    ),
                    MenuItemButton(
                      onPressed: () => _activate(MenuEntry.colorBlue),
                      shortcut: MenuEntry.colorBlue.shortcut,
                      child: Text(MenuEntry.colorBlue.label),
                    ),
                  ],
                  child: const Text('Background Color'),
                ),
              ],
              builder: (BuildContext context, MenuController controller, Widget? child) {
                return TextButton(
                  focusNode: _buttonFocusNode,
                  onPressed: () {
                    if (controller.isOpen) {
                      controller.close();
                    } else {
                      controller.open();
                    }
                  },
                  child: const Text('OPEN MENU'),
                );
              },
            ),
            Expanded(
              child: CallbackShortcuts(
                bindings: <ShortcutActivator, VoidCallback>{
                  const SingleActivator(LogicalKeyboardKey.escape): () {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('Escape key handler triggered'),
                        duration: Duration(seconds: 1),
                      ),
                    );
                  },
                },
                child: Focus(
                  focusNode: _containerFocusNode,
                  child: Container(
                    alignment: Alignment.center,
                    color: backgroundColor,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.all(12.0),
                          child: Text(
                            showingMessage ? widget.message : '',
                            style: Theme.of(context).textTheme.headlineSmall,
                          ),
                        ),
                        Text(_lastSelection != null ? 'Last Selected: ${_lastSelection!.label}' : ''),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        );
      }
    
      void _activate(MenuEntry selection) {
        setState(() {
          _lastSelection = selection;
        });
    
        switch (selection) {
          case MenuEntry.about:
            showAboutDialog(
              context: context,
              applicationName: 'MenuBar Sample',
              applicationVersion: '1.0.0',
            );
          case MenuEntry.hideMessage:
          case MenuEntry.showMessage:
            showingMessage = !showingMessage;
          case MenuEntry.colorMenu:
            break;
          case MenuEntry.colorRed:
            backgroundColor = Colors.red;
          case MenuEntry.colorGreen:
            backgroundColor = Colors.green;
          case MenuEntry.colorBlue:
            backgroundColor = Colors.blue;
        }
      }
    }
    
    class MenuApp extends StatelessWidget {
      const MenuApp({super.key});
    
      static const String kMessage = '"Talk less. Smile more." - A. Burr';
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          theme: ThemeData(useMaterial3: true),
          home: const Scaffold(body: MyCascadingMenu(message: kMessage)),
        );
      }
    }
  7. added
    r: fixedIssue is closed as already fixed in a newer version
    on Oct 11, 2023
  8. github-actions commented on Oct 25, 2023

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

  9. locked as resolved and limited conversation to collaborators on Oct 25, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

P2Important issues not at the top of the work lista: desktopRunning on desktopa: mouseIssues related to using a mouse or mouse supportfound in release: 3.13Found to occur in 3.13found in release: 3.15Found to occur in 3.15frameworkflutter/packages/flutter repository. See also f: labels.has reproducible stepsThe issue has been confirmed reproducible and is ready to work onp: material_uimaterial_ui package in flutter/packagesr: fixedIssue is closed as already fixed in a newer versionteam-designOwned by Design Languages teamtriaged-designTriaged by Design Languages team

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions