/
products.dart
172 lines (159 loc) · 5.44 KB
/
products.dart
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../models/http_exception.dart';
import './product.dart';
class Products with ChangeNotifier {
List<Product> _items = [
// Product(
// id: 'p1',
// title: 'Red Shirt',
// description: 'A red shirt - it is pretty red!',
// price: 29.99,
// imageUrl:
// 'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
// ),
// Product(
// id: 'p2',
// title: 'Trousers',
// description: 'A nice pair of trousers.',
// price: 59.99,
// imageUrl:
// 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Trousers%2C_dress_%28AM_1960.022-8%29.jpg/512px-Trousers%2C_dress_%28AM_1960.022-8%29.jpg',
// ),
// Product(
// id: 'p3',
// title: 'Yellow Scarf',
// description: 'Warm and cozy - exactly what you need for the winter.',
// price: 19.99,
// imageUrl:
// 'https://live.staticflickr.com/4043/4438260868_cc79b3369d_z.jpg',
// ),
// Product(
// id: 'p4',
// title: 'A Pan',
// description: 'Prepare any meal you want.',
// price: 49.99,
// imageUrl:
// 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Cast-Iron-Pan.jpg/1024px-Cast-Iron-Pan.jpg',
// ),
];
// var _showFavoritesOnly = false;
List<Product> get items {
// if (_showFavoritesOnly) {
// return _items.where((prodItem) => prodItem.isFavorite).toList();
// }
return [..._items];
}
List<Product> get favoriteItems {
return _items.where((prodItem) => prodItem.isFavorite).toList();
}
Product findById(String id) {
return _items.firstWhere((prod) => prod.id == id);
}
// void showFavoritesOnly() {
// _showFavoritesOnly = true;
// notifyListeners();
// }
// void showAll() {
// _showFavoritesOnly = false;
// notifyListeners();
// }
Future<void> fetchAndSetProducts() async {
final url = Uri.https(
'fluttershopapp-e471e-default-rtdb.firebaseio.com', '/products.json');
try {
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
if (extractedData == null) {
return;
}
final List<Product> loadedProducts = [];
extractedData.forEach((prodId, prodData) {
loadedProducts.add(Product(
id: prodId,
title: prodData['title'],
description: prodData['description'],
price: prodData['price'],
isFavorite: prodData['isFavorite'],
imageUrl: prodData['imageUrl'],
));
});
_items = loadedProducts;
notifyListeners();
} catch (error) {
throw (error);
}
}
// ********** besoin we want to return A Future (helpfull to insert navigation code and loading in Widget) unstead of passing everthing as params like Lineosoft :p ********
// *************** 1- Using then **********
// if we were using then and we want to return a Future
// Problem return inside then (nested sucess block does not trigurer function to return)
// Solution
// retun the hole block return http.post(....)
// *************** 2- Using assync await **********
// addProduct type is Future but don't return anything void
Future<void> addProduct(Product product) async {
// https://fluttershopapp-e471e-default-rtdb.firebaseio.com/
final url = Uri.https(
'fluttershopapp-e471e-default-rtdb.firebaseio.com', '/products.json');
try {
final response = await http.post(
url,
body: json.encode({
'title': product.title,
'description': product.description,
'imageUrl': product.imageUrl,
'price': product.price,
'isFavorite': product.isFavorite,
}),
);
final newProduct = Product(
title: product.title,
description: product.description,
price: product.price,
imageUrl: product.imageUrl,
id: json.decode(response.body)['name'],
);
_items.add(newProduct);
// _items.insert(0, newProduct); // at the start of the list
notifyListeners();
} catch (error) {
print(error);
throw error;
}
}
Future<void> updateProduct(String id, Product newProduct) async {
final prodIndex = _items.indexWhere((prod) => prod.id == id);
if (prodIndex >= 0) {
final url = Uri.https('fluttershopapp-e471e-default-rtdb.firebaseio.com',
'/products/$id.json');
await http.patch(url,
body: json.encode({
'title': newProduct.title,
'description': newProduct.description,
'imageUrl': newProduct.imageUrl,
'price': newProduct.price
}));
_items[prodIndex] = newProduct;
notifyListeners();
} else {
print('...');
}
}
Future<void> deleteProduct(String id) async {
final url = Uri.https('fluttershopapp-e471e-default-rtdb.firebaseio.com',
'/products/$id.json');
final existingProductIndex = _items.indexWhere((prod) => prod.id == id);
var existingProduct = _items[existingProductIndex];
_items.removeAt(existingProductIndex);
notifyListeners();
final response = await http.delete(url);
if (response.statusCode >= 400) {
_items.insert(existingProductIndex, existingProduct);
notifyListeners();
throw HttpException('Could not delete product.');
}
existingProduct = null;
}
}