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

Issue

For example, I may have one RichText in current widget tree, that looks like

RichText(
 text: TextSpan(
   text: 'Hello ',
   style: DefaultTextStyle.of(context).style,
   children: <TextSpan>[
     TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
     TextSpan(text: ' world!'),
   ],
 ),
)

I try to use find.text('Hello bold world!') but it doesn’t work because it’s not a Text.

Solution

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.

Answered By – Ian Hickson

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *