在PopupMenuItem点击时不显示Flutter showDialog

mqxuamgl  于 2023-05-29  发布在  Flutter
关注(0)|答案(2)|浏览(161)

我在应用程序中使用PopupMenuButton。我想在点击PopupMenuItemshowDialog
我的PopupMenuItem

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

PopupMenuButton内部使用onSelected也不起作用。

w6mmgewl

w6mmgewl1#

这是因为popupMenuItem的onTap试图使用Navigator.pop来关闭弹出窗口,但同时您试图显示对话框,因此它关闭对话框并离开弹出窗口,因此,您可以等到所有动画或正在进行的事情完成后再显示对话框
代码: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'),
                            ),
                          ],
                        );
                      });
                });
              }),
z9gpfhce

z9gpfhce2#

试试这个:

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

相关问题