首页 > 解决方案 > 即使它在树中也无法按键找到小部件

问题描述

即使在小部件树中,在测试中也无法通过键找到小部件的可能原因是什么?

所以在我的应用程序中,我有一些网站类别,每个类别都有一个 + 按钮,因此用户可以添加自己的。现在,我想测试按下 + 按钮时页面是否正确打开。如果我这样做:

await tester.tap(find.byIcon(Icons.add));

测试失败是因为它发现了太多的小部件并且不知道要点击哪一个。所以我想我会通过将它们包装在这样的容器中来为我的 + 按钮提供键:

Container(
    key: ValueKey('add_website_' + category.toLowerCase()),
    child: AddWebsiteButton(),  // the tappable widget that contains an Icon(Icons.add)
)

现在在我的测试中,我调用:

expect(find.byKey(ValueKey('add_website_learning')), findsOneWidget);

而且,你瞧,它失败了:

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following TestFailure object was thrown running a test:
  Expected: exactly one matching node in the widget tree
  Actual: _KeyFinder:<zero widgets with key [<'add_website_learning'>] (ignoring offstage widgets)>
   Which: means none were found but one was expected

如果我debugDumpApp()在上面的调用之前调用,我可以看到具有该键的 Container 实际上位于小部件树中:

...
└KeyedSubtree-[Key <[<add_website_learning>]>]
  └AutomaticKeepAlive(state: _AutomaticKeepAliveState#470b4(handles: no notifications ever received))
    └KeepAlive(keepAlive: false)
      └NotificationListener<KeepAliveNotification>
        └IndexedSemantics(index: 4, renderObject: RenderIndexedSemantics#02bbd relayoutBoundary=up3 NEEDS-PAINT)
          └RepaintBoundary(renderObject: RenderRepaintBoundary#8170e relayoutBoundary=up4 NEEDS-PAINT)
            └Container-[<add_website_learning>]
              └Tooltip("Add website", dependencies: [_LocalizationsScope-[GlobalKey#55b7a], _InheritedTheme, TickerMode-[<CrossFadeState.showSecond>]], state: _TooltipState#87315(ticker inactive))
                └GestureDetector(startBehavior: start)
...

我尝试通过调用来确保它在视图中ensureVisible,但这也未能说明它找不到小部件。

我究竟做错了什么?

标签: flutterflutter-test

解决方案


推荐阅读