UI libraries / Algolia for Flutter / Widgets

About this widget

A great search interface highlights parts of the search results to explain why they’re relevant to users. With Flutter Helper, the HighlightedString objects simplify highlighting the right words in a search response that match your query.

You can read more about the concept of highlighting in the highlighting guide.

Examples

Lets take the example of an index containing movies. Each movie record has a title field. Here is what the search engine response for a query "red" could look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
  "objectID": "439817390",
  "title": "The Shawshank Redemption",
  "_highlightResult": {
    "title": {
      "value": "The Shawshank <em>Red</em>emption",
      "matchLevel": "full",
      "fullyHighlighted": false,
      "matchedWords": [
        "red"
      ]
    }
  }
}

To display those movies in your interface, you likely have created a data class that looks something like the following:

1
2
3
4
5
6
7
8
9
10
11
class Movie {

  String? title;

  Movie({this.title});

  static Movie fromHit(Hit hit) {
    return Movie(title: hit['title']);
  }

}

It includes a static method to build a Movie instance from the Hit object.

Extract highlighted strings from search hit JSON

Complete the Movie class with the highlightedTitle property of the HighlightedString type. Update the fromJson method so that it parses the HighlightedString from the hit using the getHighlightedString method.

1
2
3
4
5
6
7
8
9
10
11
12
class Movie {
  String? title;
  HighlightedString? highlightedTitle;

  Movie({this.title, this.highlightedTitle});

  static Movie fromJson(Hit hit) {
    return Movie(
        title: hit['title'],
        highlightedTitle: hit.getHighlightedString('title'));
  }
}

A HighlightedString can be created directly from the raw tagged string.

1
2
final rawHighlightedTitle = 'The Shawshank <em>Red</em>emption';
final highlightedTitle = HighlightedString.of(rawHighlightedTitle);

Using highlighted strings in Flutter

The HighlightedString provides a toInlineSpans() method which produces a list of InlineSpan instances. The highlightedTextStyle parameter of this method defines the style of the highlighted part of the text. These instances, in turn, can be used as a parameter in the RichText Flutter widget as follows:

1
2
3
4
5
RichText(
    text: TextSpan(
        style: const TextStyle(color: Colors.black),
        children: movie.highlightedTitle!.toInlineSpans(
            highlightedTextStyle: const TextStyle(color: Colors.orange))));
Did you find this page helpful?