Normally to find an entire string you can use find.text()
like this:
expect(find.text('text to find'), findsOneWidget);
What about finding a substring in a Text
widget? Say there was text of 'text to find'
, and we just wanted to check that 'to'
is a part of a Text
widget.
By using find.byWidgetPredicate
, you can specify your own validation predicate and thus check everything you want like a substring of the text.
eg :
expect(find.byWidgetPredicate((widget) {
if (widget is Text) {
final Text textWidget = widget;
if (textWidget.data != null)
return textWidget.data.contains('mySubstr');
return textWidget.textSpan.toPlainText().contains('mySubstr');
}
return false;
}), findsOneWidget);
Now using dart extension methods we can write more readable tests.
First, add a new method to the CommonFinders class:
extension CustomFinders on CommonFinders {
Finder textMatch(Pattern pattern, {bool skipOffstage = true}) =>
_PatternMatchFinder(pattern, skipOffstage: skipOffstage);
}
class _PatternMatchFinder extends MatchFinder {
_PatternMatchFinder(this.pattern, {bool skipOffstage = true}) : super(skipOffstage: skipOffstage);
final Pattern pattern;
@override
String get description => 'textMatch "$pattern"';
@override
bool matches(Element candidate) {
final Widget widget = candidate.widget;
if (widget is Text) {
if (widget.data != null) return pattern.allMatches(widget.data).isNotEmpty;
return pattern.allMatches(widget.textSpan.toPlainText()).isNotEmpty;
} else if (widget is EditableText) {
return pattern.allMatches(widget.controller.text).isNotEmpty;
}
return false;
}
}
And now our tests look like this:
expect(find.textMatch('Back'), findsOneWidget);
expect(find.textMatch(RegExp(r'\s*Back.*')), findsOneWidget);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With