I wrote a quick function that returns a List of TextSpan
.
Function matches the query string against the source string, enumerating the matches one by one, cutting the source string into pieces: before the match, after the match, and the match itself - making it bold.
It is intended to be used in a RichText
widget.
List<TextSpan> highlightOccurrences(String source, String query) {
if (query.isEmpty || !source.toLowerCase().contains(query.toLowerCase())) {
return [ TextSpan(text: source) ];
}
final matches = query.toLowerCase().allMatches(source.toLowerCase());
int lastMatchEnd = 0;
final List<TextSpan> children = [];
for (var i = 0; i < matches.length; i++) {
final match = matches.elementAt(i);
if (match.start != lastMatchEnd) {
children.add(TextSpan(
text: source.substring(lastMatchEnd, match.start),
));
}
children.add(TextSpan(
text: source.substring(match.start, match.end),
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
));
if (i == matches.length - 1 && match.end != source.length) {
children.add(TextSpan(
text: source.substring(match.end, source.length),
));
}
lastMatchEnd = match.end;
}
return children;
}
Example based on your code:
Text.rich(
TextSpan(
children: highlightOccurrences(suggestList[index].d, query),
style: TextStyle(color: Colors.grey),
),
),
Let me know if this helped.