首页 > 解决方案 > Flutter:ShowDialog 不能与 ListTile 的 OnTap() 方法一起使用

问题描述

我正在使用一个抽屉来创建一个包含选项的 ListTiles 的菜单。我想在用户点击瓷砖时创建一个弹出窗口。目前,即使在 showDialog 之后有一个 Navigator.pop(),当点击图块时代码也不显示任何内容。

// Drawer that includes the ListTiles in question
 Drawer(
          child: ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              DrawerHeader(
                child: Text('Smash Tracker'),
                ),
              ),
              ListTile(
                title: Text(
                    'About',
                  style: TextStyle(
                    fontFamily: 'Smash',
                    fontSize: 15.0,
                    color: Color.fromRGBO(77, 114, 152, 1.0),
                  ),
                ),
                onTap: () {
                  // Show PopUp
                  showDialog(context: context, child:
                    new AlertDialog(
                      title: new Text(
                        'About',
                        style: TextStyle(fontFamily: "Smash"),
                      ),
                      content: new Text(
                        'This is a placeholder. This is a placeholder. This is a placeholder. This is a placeholder.',
                        style: TextStyle(fontFamily: "Smash"),
                      ),
                    )
                  );

                  // Doesn't run
                  Navigator.pop(context);
                },
              ),

这是一个演示:

通过 GIPHY

其他 ListTiles 在其 onTap() 方法中只有 Navigator.pop()。

标签: flutterdartshowdialog

解决方案


该对话框未显示,因为您立即使用Navigator.pop(context). 你可以awaitDialog因为它Future<T>在弹出之前返回一个。

我以您的小部件树为例添加了一个演示:

Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              child: Text('Smash Tracker'),
            ),
            ListTile(
              title: Text(
                'About',
                style: TextStyle(
                  fontFamily: 'Smash',
                  fontSize: 15.0,
                  color: Color.fromRGBO(77, 114, 152, 1.0),
                ),
              ),
              onTap: () async { // mark the function as async
                print('tap');
                // Show PopUp

                // await the dialog
                 await showDialog(
                    context: context,
                    child: new AlertDialog(
                      title: new Text(
                        'About',
                        style: TextStyle(fontFamily: "Smash"),
                      ),
                      content: new Text(
                        'This is a placeholder. This is a placeholder. This is a placeholder. This is a placeholder.',
                        style: TextStyle(fontFamily: "Smash"),
                      ),
                    ));

                // Doesn't run
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),

输出:

在此处输入图像描述


推荐阅读