highlightMatch method

Widget highlightMatch(
  1. String text,
  2. String query
)

Highlights the parts of text that match the query string.

This method returns a RichText widget with matching substrings highlighted using a yellow background and bold font. If the query is empty, it simply returns the original text wrapped in a Text widget.

Useful for displaying search results where you want to visually emphasize the parts of the text that match the user's input.

Example:

highlightMatch('Flutter Searchify', 'search')

will return a widget with the word "Search" highlighted.

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,
    ),
  );
}