Guides
/
Building Search UI
/
Ecommerce ui template
/
Components
/
Data sources
May. 03, 2022
SuggestionRepository
On this page
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 the [community Algolia Dart client][https://pub.dev/packages/algolia] and local 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
class SuggestionRepository {
SuggestionRepository._internal();
static final SuggestionRepository _instance =
SuggestionRepository._internal();
factory SuggestionRepository() {
return _instance;
}
final Algolia _algoliaClient = Algolia.init(
applicationId: Credentials.applicationID,
apiKey: Credentials.searchOnlyKey);
final List<String> _history = ['jackets'];
/// Get suggestions for a query.
Future<List<QuerySuggestion>> getSuggestions(Query query) async {
AlgoliaQuery algoliaQuery =
_algoliaClient.instance.index(Credentials.suggestionsIndex);
algoliaQuery = query.apply(algoliaQuery);
AlgoliaQuerySnapshot snap = await algoliaQuery.getObjects();
final hits = snap.toMap()["hits"];
return List<QuerySuggestion>.from(
hits.map((hit) => QuerySuggestion.fromJson(hit)));
}
List<String> getHistory() {
return _history;
}
void addToHistory(String query) {
if (query.isEmpty) return;
_history.removeWhere((element) => element == query);
_history.add(query);
}
void removeFromHistory(String query) {
_history.removeWhere((element) => element == query);
}
void clearHistory() {
_history.clear();
}
}
Did you find this page helpful?