8

I'm using PopupMenuButton in my application. I want to showDialog on tapping a PopupMenuItem.

My PopupMenuItem:

PopupMenuItem(
    child: Text("Show dialog"),
    onTap: () { 
        showDialog(
            context: context,
            barrierColor: Colors.black26,
            builder: (context) => AlertDialog( 
            ...
        )
    },
),

Also using onSelected inside the PopupMenuButton didn't work.

genericUser
  • 4,417
  • 1
  • 28
  • 73

2 Answers2

18

Thats because onTap of popupMenuItem tries to use Navigator.pop to close the popup but at same time you are trying to show the dialog, So it closes the dialog and leaves the popup so, you can wait till the all the animations or ongoing things complete then show dialog

code: dartPad code

 PopupMenuItem(
              child: const Text('Item 0'),
              onTap: () {
                WidgetsBinding?.instance?.addPostFrameCallback((_) {
                  showCupertinoDialog(
                      context: context,
                      builder: (context) {
                        return CupertinoAlertDialog(
                          title: const Icon(CupertinoIcons.info_circle),
                          content: const Text(
                            'Hello User, Welcome',
                            textAlign: TextAlign.center,
                          ),
                          actions: [
                            CupertinoDialogAction(
                              isDefaultAction: true,
                              onPressed: () => Navigator.pop(context),
                              child: const Text('Thanks'),
                            ),
                          ],
                        );
                      });
                });
              }),
Mohan Sai Manthri
  • 2,808
  • 1
  • 11
  • 26
9

Try this one:

PopupMenuItem(
  child: Text("Show dialog"),
  onTap: () { 
      Future<void>.delayed(
        Duration.zero,
        () => showDialog(
              context: context,
              barrierColor: Colors.black26,
              builder: (context) => AlertDialog(...),
        ),
    ),
  },
);
Hamed
  • 5,867
  • 4
  • 32
  • 56