Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a TextSpan to tap on with Flutter tests

With a Flutter WidgetTester how can you tap on a TextSpan, like in the code below?

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'),
    ],
  ),
)
like image 733
Benno Richters Avatar asked Feb 16 '20 10:02

Benno Richters


1 Answers

CommonFinders byWidgetPredicate method

InlineSpan visitChildren method

Find the 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;
}
like image 100
Kahou Avatar answered Nov 10 '22 01:11

Kahou