'How to highlight correct word on searchDelegate?

I highlighted the word, but not the correct word.

In my BuilderSuggection, I added like this code,

check my searchDelegate

 title: RichText(
          text: TextSpan(
              text: suggestList[index].d.substring(0, query.length),
              style: TextStyle(
                  color: Colors.black, fontWeight: FontWeight.bold),
              children: [
            TextSpan(
                text: suggestList[index].d.substring(query.length),
                style: TextStyle(color: Colors.grey))
          ])),


Solution 1:[1]

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 == null || 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:

RichText(
  text: TextSpan(
    children: highlightOccurrences(suggestList[index].d, query),
    style: TextStyle(color: Colors.grey),
  ),
),

Let me know if this helped.

Solution 2:[2]

Based on @George's answer there is a similar function with the only difference that the query is first split by spaces and each separate word is then highlighted. It took me a while to make it work properly so why not to share:

List<TextSpan> highlightOccurrences(String source, String query) {
  if (query == null || query.isEmpty) {
    return [TextSpan(text: source)];
  }

  var matches = <Match>[];
  for (final token in query.trim().toLowerCase().split(' ')) {
    matches.addAll(token.allMatches(source.toLowerCase()));
  }

  if (matches.isEmpty) {
    return [TextSpan(text: source)];
  }
  matches.sort((a, b) => a.start.compareTo(b.start));

  int lastMatchEnd = 0;
  final List<TextSpan> children = [];
  for (final match in matches) {
    if (match.end <= lastMatchEnd) {
      // already matched -> ignore
    } else if (match.start <= lastMatchEnd) {
      children.add(TextSpan(
        text: source.substring(lastMatchEnd, match.end),
        style: TextStyle(fontWeight: FontWeight.bold, color: Colors.black),
      ));
    } else 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 (lastMatchEnd < match.end) {
      lastMatchEnd = match.end;
    }
  }

  if (lastMatchEnd < source.length) {
    children.add(TextSpan(
      text: source.substring(lastMatchEnd, source.length),
    ));
  }

  return children;
}

The usage is the same as with @George's answer:

RichText(
  text: TextSpan(
    children: highlightOccurrences(suggestList[index].d, query),
    style: TextStyle(color: Colors.grey),
  ),
),

Solution 3:[3]

Sorry for my very late answer, but I wanted to give also my support for this kind of "problem".

I wanted to find a different way, and I figured it out without using if statements, which is pretty nice looking, and maybe even easier to manage it; I considered the "suggestion string" as divided in the worst case scenario of 3 substrings: 2 strings on the side, and one in the center. The center one, as you can imagine is the "bold" one. That's it! If there's no correspondence, obviously there will be no result shown in suggestion box. I directly copy&pasted the same code I used.

return ListView.builder(
        itemCount: _posts.length,
        itemBuilder: (context, index) {
          int startIndex = _posts[index].title.toLowerCase().indexOf(query.toLowerCase());
          return ListTile(
            title: query.isEmpty
                ? Text(_posts[index].title)
                : RichText(
                    text: TextSpan(
                    text: _posts[index].title.substring(0, startIndex),
                    style: TextStyle(color: Colors.grey),
                    children: [
                      TextSpan(
                        text: _posts[index]
                            .title
                            .substring(startIndex, startIndex + query.length),
                        style: TextStyle(
                            fontWeight: FontWeight.bold, color: Colors.black),
                      ),
                      TextSpan(
                        text: _posts[index]
                            .title
                            .substring(startIndex + query.length),
                        style: TextStyle(color: Colors.grey),
                      )
                    ],
                  )),
            subtitle: Text(_posts[index].date),
          );

Solution 4:[4]

        //hight light occurrentces
    List<TextSpan> _highlightOccurrences(String text, String query) {
      final List<TextSpan> spans = [];
      final String lowercaseText = text.toLowerCase();
      final String lowercaseQuery = query.toLowerCase();
    
      int lastIndex = 0;
      int index = lowercaseText.indexOf(lowercaseQuery);
    
      while (index != -1) {
        spans.add(TextSpan(text: text.substring(lastIndex, index)));
        spans.add(TextSpan(text: text.substring(index, index + query.length), style: const TextStyle(fontWeight: FontWeight.bold)));
        lastIndex = index + query.length;
        index = lowercaseText.indexOf(lowercaseQuery, lastIndex);
      }
    
      spans.add(TextSpan(text: text.substring(lastIndex, text.length)));
    
      return spans;
    }



using:

    @override
      Widget buildSuggestions(BuildContext context) {
        final suggestions = lstString.where((name) {
          return name.toLowerCase().contains(query.toLowerCase());
        }).toList();
    
        //limit suggest
        const int limitSuggest = 5;
        if (suggestions.length > limitSuggest) {
          suggestions.removeRange(limitSuggest, suggestions.length);
        }
    
        return ListView.builder(
          itemCount: suggestions.length,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
              title: query.isEmpty
                  ? Text(
                      suggestions.elementAt(index),
                    )
                  : RichText(
                      text: TextSpan(
                          children: _highlightOccurrences(suggestions[index], query), style: TextStyle(color: Theme.of(context).colorScheme.onSurface)),
                    ),
              onTap: () => query = suggestions.elementAt(index),
            );
          },
        );

  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user9139407
Solution 2 Ikar Pohorský
Solution 3 sharkpowah
Solution 4 Eric Aya