寻找TextSpan以使用Flutter测试

时间:2020-02-16 10:01:15

标签: flutter flutter-test

如何使用Flutter WidgetTester像下面的代码一样点击TextSpan?

RichText(
  text: TextSpan(
    children: [
      TextSpan(text: 'aaa '),
      TextSpan(
        text: 'bbb ',
        recognizer: TapGestureRecognizer()
          ..onTap = () { 
            // How to reach this code in a widget test?
          },
      ),
      TextSpan(text: 'ccc'),
    ],
  ),
)

1 个答案:

答案 0 :(得分:5)

CommonFinders byWidgetPredicate method

InlineSpan visitChildren method

查找TextSpan:

final finder = find.byWidgetPredicate(
  (widget) => widget is RichText && tapTextSpan(widget, "bbb "),
);
bool findTextAndTap(InlineSpan visitor, String text) {
  if (visitor is TextSpan && visitor.text == text) {
    (visitor.recognizer as TapGestureRecognizer).onTap();

    return false;
  }

  return true;
}

bool tapTextSpan(RichText richText, String text) {
  final isTapped = !richText.text.visitChildren(
    (visitor) => findTextAndTap(visitor, text),
  );

  return isTapped;
}