Home > Enterprise >  Flutter showDialog is not shown on PopupMenuItem tap
Flutter showDialog is not shown on PopupMenuItem tap

Time:10-15

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.

CodePudding user response:

Try this one:

PopupMenuItem(
  child: Text("Show dialog"),
  onTap: () { 
      Future<void>.delayed(
        const Duration(milliseconds: 500),  // OR const Duration(),
        () => showDialog(
              context: context,
              barrierColor: Colors.black26,
              builder: (context) => AlertDialog( 
              ...
          ),
      ),
  },
);

CodePudding user response:

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'),
                            ),
                          ],
                        );
                      });
                });
              }),
  • Related