Is there an easy way to find particular text built from RichText in a Flutter test?

Simplest solution is to put a key on the RichText and read it that way.

If that's not a good fit for whatever reason, you can use find.byWidgetPredicate and pass a function that matches RichText widgets whose text.toPlainText() returns the string you want.


Here's the find.byWidgetPredicate call.

find.byWidgetPredicate((widget) => fromRichTextToPlainText(widget) == 'Hello bold world!')

Here's the fromRichTextToPlainText helper function. Pass it the RichText widget, it will return the plain text.

String fromRichTextToPlainText(final Widget widget) {
  if (widget is RichText) {
    if (widget.text is TextSpan) {
      final buffer = StringBuffer();
      (widget.text as TextSpan).computeToPlainText(buffer);
      return buffer.toString();
    }
  }
  return null;
}

Tags:

Flutter