buildHighlightSpans function
Build text spans highlighting matches of query in text.
matchIndices contains the starting indices of each occurrence.
The match at the current index (specified by currentMatchIndex)
is highlighted in other color.
Implementation
List<TextSpan> buildHighlightSpans(
String text,
String query,
List<int> matchIndices,
int currentMatchIndex,
) {
List<TextSpan> spans = [];
if (query.isEmpty || matchIndices.isEmpty) {
spans.add(TextSpan(text: text, style: monoSmallTextStyle));
return spans;
}
int start = 0;
final queryLength = query.length;
// Iterate with an index so we know which match is the current one.
for (int i = 0; i < matchIndices.length; i++) {
final index = matchIndices[i];
if (index > start) {
spans.add(
TextSpan(text: text.substring(start, index), style: monoSmallTextStyle),
);
}
// Use green for the current match, yellow for others.
Color highlightColor =
(i == currentMatchIndex) ? Colors.lightGreen : Colors.yellow;
spans.add(
TextSpan(
text: text.substring(index, index + queryLength),
style: monoSmallTextStyle.copyWith(backgroundColor: highlightColor),
),
);
start = index + queryLength;
}
// Add any remaining text after the last match.
if (start < text.length) {
spans.add(TextSpan(text: text.substring(start), style: monoSmallTextStyle));
}
return spans;
}