Testing text in TextSpan
In addition to Rémi's answer, here is the way to find the text from a RichText
.
You set the key to the RichText
and then you can do:
Finder widgetFinder = find.byKey(key);
Finder rtFinder =
find.descendant(of: widgetFinder, matching: find.byType(RichText));
RichText richText = rtFinder.evaluate().first.widget as RichText;
String richTextText = richText.text.toPlainText();
print('Text from Text widget: $richTextText');
expect(richTextText, 'This is my text',
reason: 'Text from found text widget do not match');
You can find the RichText widget instead. Here's the find.byWidgetPredicate call.
expect(find.byWidgetPredicate((widget) => fromRichTextToPlainText(widget) == 'Hello world!'), findsOneWidget);
Here's the fromRichTextToPlainText helper function. Pass it the RichText widget, it will return the plain text for all the underlying TextSpans.
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;
}
That's not possible. As TextSpan
doesn't actually render anything.
It is data information used by another object to actually render something.
What you can do instead is to find the widget to which you pass your TextSpan
. And then verify it's correct