首页 > 解决方案 > 如何在 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它是 Widget 类型,它不等于 String toffee

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

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

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

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

标签: testingtextdartflutter

解决方案


您可以将您firstCell的投到Text.

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

然后测试firstCell.data

expect(firstCell.data, 'toffee');

推荐阅读