Guides
        /
          Building Search UI
        /
          Ecommerce ui template
        /
          Components
        /
          Data sources
        /
          Suggestion repository
  
        
          
          
          
        
        Oct. 21, 2022
      
  SuggestionRepository
On this page
Algolia for Flutter is beta software according to Algolia’s Terms of Service (“Beta Services”). To share feedback or report a bug, open an issue.
Code summary
SuggestionRepository provides convenient methods to get query suggestions.
There are two types of query suggestions:
- Search completions updated on each keystroke.
 - Search history retaining the submitted queries.
 
The SuggestionRepository component encapsulates Flutter Helpers and local (in-memory) query history storage. 
Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class SuggestionRepository {
  /// Hits Searcher for suggestions index
  final _suggestionsSearcher = HitsSearcher(
    applicationID: Credentials.applicationID,
    apiKey: Credentials.searchOnlyKey,
    indexName: Credentials.suggestionsIndex,
  );
  /// Get query suggestions for a given query string.
  void query(String query) {
    _suggestionsSearcher.query(query);
  }
  /// Get query suggestions stream
  late final Stream<List<QuerySuggestion>> suggestions = _suggestionsSearcher
      .responses
      .map((response) => response.hits.map(QuerySuggestion.fromJson).toList());
  /// In-memory store of submitted queries.
  final BehaviorSubject<List<String>> _history =
      BehaviorSubject.seeded(['jackets']);
  /// Stream of previously submitted queries.
  Stream<List<String>> get history => _history;
  /// Add a query to queries history store.
  void addToHistory(String query) {
    if (query.isEmpty) return;
    final _current = _history.value;
    _current.removeWhere((element) => element == query);
    _current.add(query);
    _history.sink.add(_current);
  }
  /// Remove a query from queries history store.
  void removeFromHistory(String query) {
    final _current = _history.value;
    _current.removeWhere((element) => element == query);
    _history.sink.add(_current);
  }
  /// Clear everything from queries history store.
  void clearHistory() {
    _history.sink.add([]);
  }
  /// Dispose of underlying resources.
  void dispose() {
    _suggestionsSearcher.dispose();
  }
}
      
Did you find this page helpful?