Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 659
Wei Song Avatar asked Dec 14 '16 21:12

Wei Song


3 Answers

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.

like image 129
Ian Hickson Avatar answered Oct 03 '22 00:10

Ian Hickson


Framework solution

I have recently contributed this feature to the Flutter framework, i.e. to the built-in finders.

find.text()

You can now enable a findRichText parameter, which will then also find standalone RichText widgets:

find.text(
  'Hello bold world!',
  findRichText: true,
)
like image 33
creativecreatorormaybenot Avatar answered Oct 03 '22 01:10

creativecreatorormaybenot


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;
}
like image 34
Bienvenido David Avatar answered Oct 03 '22 00:10

Bienvenido David