如何在 Flutter 中测试期间找到 Widget 的 'text' 属性?



>我有一段代码可以创建一个文本目录小部件,如下所示:

return Table(
defaultColumnWidth: FixedColumnWidth(120.0),
children: <TableRow>[
TableRow(
children: <Widget>[Text('toffee'), Text('potato')],
),
TableRow(
children: <Widget>[Text('cheese'), Text('pie')],
),
],
);

我想测试表中的第一项确实是"太妃糖"一词。我设置了测试并进入了这一部分:

var firstCell = find
.descendant(
of: find.byType(Table),
matching: find.byType(Text),
)
.evaluate()
.toList()[0].widget;
expect(firstCell, 'toffee');

这绝对不起作用,因为firstCell是小部件类型,它不等于字符串toffee

我只看到一个toString()函数,如下所示:

'Text("toffee", inherit: true, color: Color(0xff616161), size: 16.0,
textAlign: left)'

如何提取text属性以获取单词toffee

现在看来,我所能做的就是检查.toString().contains('toffee')是否不理想。

Rémi 的例子不太有效 - 它可能在他回答时有效,但此时调用whereType<Text>()将始终返回一个空Iterable,因为evaluate()返回Iterable<Element>,而不是Iterable<Widget>。但是,您可以通过调用Element的 Widget 来获取它.widget,因此以下代码应该有效:

Text firstText = find
.descendant(
of: find.byType(Table),
matching: find.byType(Text),
)
.evaluate()
.first
.widget;
expect(firstText.data, 'toffee');

OP 非常接近拥有工作代码 - 只有 2 个小问题:

  • 通过使用var而不是Text,变量的类型被Widget
  • WidgetString进行比较 - 这永远不会返回 true - 目的是将Widget的属性与String进行比较 - 在Text的情况下,它显示的String是通过调用.data来获得的Text

编辑:

WidgetTester现在具有用于检索小部件的实用程序函数:widget(Finder)widgetList(Finder)firstWidget(Finder)allWidgets。因此,对于OP的用例,您将使用如下firstWidget

Text firstText = tester.firstWidget(
find.descendant(
of: find.byType(Table),
matching: find.byType(Text),
));
expect(firstText.data, 'toffee');

您可以将firstCell投射到Text

var firstCell = find
.descendant(
of: find.byType(Table),
matching: find.byType(Text),
)
.evaluate()
.whereType<Text>()
.first;

然后测试firstCell.data

expect(firstCell.data, 'toffee');

按文本查找 ?

expect(find.text('toffee'), findsOneWidget);

您可以对任何类型的小部件使用简写形式:

expect(
(find.byType(InAppWebView).evaluate().single.widget as InAppWebView)
.initialUrl,
'https://www.google.com/');

相关内容

最新更新