我可以检查给定元素是否存在吗? find 在找不到任何匹配元素时会抛出错误吗?

Can I check for existence of a given element? Does find throw errors when it cannot find any matching elements?

我想使用 Flutter 编写一个测试来检查给定元素是否存在。我该怎么做?

另外,如果找不到任何匹配的元素,测试会抛出错误吗?

是的,你可以使用find utility (or more generally the Finder class). Finders are quite powerful in what you can express with them, including checking for existence of widgets in the UI or even check how many of them are there. We have plenty of examples in the framework tests。以下是一些示例:

// check that MyWidget is displayed
expect(find.byType(MyWidget), findOneWidget);

// check that 5 widgets of type MyWidgets are displayed
expect(find.byType(MyWidget), findNWidgets(5));

查找器本身不会抛出错误,但 expect 会在匹配器(例如 findOneWidget)不满足时抛出错误。如果您需要与小部件交互而不是简单地声明它的存在,请使用 WidgetTester 中的方法之一,例如:

// Get the layout size of the render object for the given widget
tester.renderObject<RenderBox>(find.byType(Text)).size;