0

I've been trying to find a solution for this problem to no avail.

Is there a way in flutter (currently running version 3.22.2) to programatically close an opened DropdownMenu , ie. closing the dropdown as a reaction to something external, not via a user tap?

I've tried various methods, Including Navigator.pop(context) with a GlobalKey, but it seems that underneath the Hood DropdownMenu is using overlays to show the dropdown items, and doing a pop simply closes any window the dropdown currently resides in.

For my specific use case, I would like to close the dropdown menu whenever Android users preses the system back button.

Thank you for all your help!

PS: The highlighted issue is related to DropdownMenu widget linked above, ie the Material 3 version of Dropdown Button.

3
  • I created a DropDown and click to open it and when the DropDown is opened and I press the system's back button the DropDown is closing. Commented Jun 23, 2024 at 4:19
  • Can you share a code sample please? Which flutter version are you running? And is it with material3 enabled? Commented Jun 23, 2024 at 6:54
  • Code added in the answer, and Yes material3 is true Commented Jun 23, 2024 at 8:51

1 Answer 1

0

Unfortunately, there is no way to open or close DropdownMenu widget.

If you take a look closely in the documentation of DropdownMenu, you will find that the _DropdownMenuState class is private therefor we counldn't access the state of this widget using GobalKey besides the MenuController is instantiated privately.

DropdownMenu docs

To solve this problem we have to use another widget.

You can create your own DropdownMenu using Menu Anchor in a separate file.

In your your screen which uses the new DropdownMenu, wrap it with PopScope widget to handle back button.

PopScope(
  canPop: false,
  onPopInvoked: (bool didPop) {
    if (didPop) {
      return;
    }
    if (_controller.isOpen) {
      _controller.close();
    } else {
      Navigator.pop(context);
    }
  },
  child: ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.