Guides
/
Building Search UI
/
Ecommerce ui template
/
Components
/
Data sources
/
Product repository
Sep 11, 2024
ProductRepository
The ProductRepository
component implements the repository design pattern and includes methods to fetch product information.
It encapsulates Flutter helpers and Dart API client.
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class ProductRepository {
/// Hits Searcher with static search query `shoes`.
final _shoesSearcher = HitsSearcher.create(
applicationID: Credentials.applicationID,
apiKey: Credentials.searchOnlyKey,
state: const SearchState(
indexName: Credentials.hitsIndex,
query: 'shoes',
),
);
/// Hits Searcher with static rule contexts `home-spring-summer-2021`.
final _seasonalProductsSearcher = HitsSearcher.create(
applicationID: Credentials.applicationID,
apiKey: Credentials.searchOnlyKey,
state: const SearchState(
indexName: Credentials.hitsIndex,
ruleContexts: ['home-spring-summer-2021'],
),
);
/// Hits Searcher with static search query `jacket`.
final _recommendedProductsSearcher = HitsSearcher.create(
applicationID: Credentials.applicationID,
apiKey: Credentials.searchOnlyKey,
state: const SearchState(
indexName: Credentials.hitsIndex,
query: 'jacket',
),
);
/// Algolia API client instance.
final SearchClient _algoliaClient = SearchClient(
appId: Credentials.applicationID,
apiKey: Credentials.searchOnlyKey,
);
/// Disposable components composite
final CompositeDisposable _components = CompositeDisposable();
/// Product repository constructor.
ProductRepository() {
_components
..add(_shoesSearcher)
..add(_seasonalProductsSearcher)
..add(_recommendedProductsSearcher);
}
/// Get stream of shoes.
Stream<List<Product>> get shoes => _shoesSearcher.responses
.map((response) => response.hits.map(Product.fromJson).toList());
/// Get stream of seasonal products.
Stream<List<Product>> get seasonalProducts =>
_seasonalProductsSearcher.responses
.map((response) => response.hits.map(Product.fromJson).toList());
/// Get stream of recommended products.
Stream<List<Product>> get recommendedProducts =>
_recommendedProductsSearcher.responses.map((response) =>
response.hits.map((hit) => Product.fromJson(hit)).toList());
/// Get product by ID.
Future<Product> getProduct(String productID) async {
final rawProduct = await _algoliaClient.get(
path: '/indexes/${Credentials.hitsIndex}/$productID')
as Map<String, dynamic>;
final product = Product.fromJson(rawProduct);
return product;
}
/// Dispose of underlying resources.
void dispose() {
_components.dispose();
}
}
Did you find this page helpful?