highlightMatch method
Implementation
Widget highlightMatch(String text, String query) {
if (query.isEmpty) return Text(text);
final lcText = text.toLowerCase();
final lcQuery = query.toLowerCase();
final spans = <TextSpan>[];
int start = 0;
int index = lcText.indexOf(lcQuery);
while (index >= 0) {
if (index > start) {
spans.add(TextSpan(text: text.substring(start, index)));
}
spans.add(
TextSpan(
text: text.substring(index, index + query.length),
style: const TextStyle(
backgroundColor: Colors.yellowAccent,
fontWeight: FontWeight.bold,
),
),
);
start = index + query.length;
index = lcText.indexOf(lcQuery, start);
}
if (start < text.length) {
spans.add(TextSpan(text: text.substring(start)));
}
return RichText(
text: TextSpan(
style: const TextStyle(color: Colors.black),
children: spans,
),
);
}