specialText method
Highlights parts of the text matching regex with specialStyle and adds an optional onTap callback.
Example:
Text("Hello *world*!").specialText(
regex: r'\*(.*?)\*',
specialStyle: TextStyle(fontWeight: FontWeight.bold),
onTap: (index, text) => print("Tapped $text at $index"),
);
Implementation
Widget specialText({
required String regex,
TextStyle? specialStyle,
void Function(int index, String text)? onTap,
}) {
final textStr = data ?? '';
final matches = RegExp(regex).allMatches(textStr).toList();
if (matches.isEmpty) return this;
final spans = <TextSpan>[];
int lastIndex = 0;
final style = TextStyle(color: Colors.black).merge(this.style);
for (final match in matches) {
final index = matches.indexOf(match);
if (match.start > lastIndex) {
spans.add(
TextSpan(
text: textStr.substring(lastIndex, match.start),
style: style,
),
);
}
final t = match.group(1);
spans.add(
TextSpan(
text: t,
recognizer:
TapGestureRecognizer()
..onTap = () {
if (t != null && onTap != null) {
onTap(index, t);
}
},
style: style.merge(specialStyle),
),
);
lastIndex = match.end;
}
if (lastIndex < textStr.length) {
spans.add(TextSpan(text: textStr.substring(lastIndex), style: style));
}
return RichText(text: TextSpan(children: spans, style: style));
}