Search code examples
flutterdartflutter-test

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


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.