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.
2
Answers
Here’s the output: video
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.
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.