flutterflutter-test

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'),
    ],
  ),
)

Solution

  • 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;
    }