首页 > 解决方案 > Flutter Driver - 不定位 Flutter AlertDialog 及其元素

问题描述

我的颤振应用程序AlertDiaog中出现了颤振。使用Flutter Driver时,我无法点击 Flutter AlertDialog 或 AlertDialog 上的任何元素。有没有办法点击我的应用程序上出现的任何 AlertDialog?

我已经尝试了以下所有方法,但仍然没有运气:

  1. 第一的:
    await driver.tap(find.byType('ModalBarrier'));
    print('*******TAPPED - ModalBarrier*******');
  1. 第二
    await driver.tap(find.byType('AlertDialog'));
    print('*******TAPPED - AlertDialog*******');
  1. 第三
     await driver.tap(find.text('Gallery')); // Tapping 'Gallery', can access pics
     print('*******TAPPED - Gallery *******');

标签: flutter-alertdialogflutterdriver

解决方案


这个想法是首先AlertDialog通过唯一键识别文本,告诉驱动程序,然后对其执行tap操作。在您的主代码中,将key属性添加到Text您想要点击的父小部件,例如:我正在展示一个AlertDialog显示 2 个选项的简单内容,如下所示:

在此处输入图像描述

代码是:

showDialog(context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            content: SingleChildScrollView(
              child: ListBody(
                children: <Widget>[
                  GestureDetector(
                    key: Key('firstOptionKey'),
                    child: Text('Take a picture'),
                    onTap: () {},
                  ),
                  Padding(
                    padding: EdgeInsets.all(8.0),
                  ),
                  GestureDetector(
                    key: Key('secondOptionKey'),
                    child: Text('Select from gallery'),
                    onTap: () {},
                  ),
                ],
              ),
            ),
          );
        });

正如你所看到的,我已经将两个文本都包裹起来了GestureDetector,这样我们就可以点击它们了。此外,我使用key每个属性GestureDetector来唯一标识两个文本。

在您的驱动程序测试中,您只需识别每个文本使用byValueKey并告诉驱动程序点击它,如下所示:

test('test dialog', () async {

          final firstText = find.byValueKey('firstOptionKey');
          await driver.waitFor(find.text('Tap'));  
          await driver.tap(find.text('Tap'));   // tap on this button to open alertDialog
          await driver.waitFor(firstText);      // wait for flutter driver to locate and identify the element on screen
          await driver.tap(firstText);
          print('tapped on it');
        });

在此处输入图像描述

希望这能回答你的问题。


推荐阅读