/
orders.dart
91 lines (83 loc) · 2.33 KB
/
orders.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
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import './cart.dart';
class OrderItem {
final String id;
final double amount;
final List<CartItem> products;
final DateTime dateTime;
OrderItem({
@required this.id,
@required this.amount,
@required this.products,
@required this.dateTime,
});
}
class Orders with ChangeNotifier {
List<OrderItem> _orders = [];
List<OrderItem> get orders {
return [..._orders];
}
Future<void> fetchAndSetOrders() async {
final url = Uri.https(
'fluttershopapp-e471e-default-rtdb.firebaseio.com', '/orders.json');
final response = await http.get(url);
final List<OrderItem> loadedOrders = [];
final extractedData = json.decode(response.body) as Map<String, dynamic>;
if (extractedData == null) {
return;
}
extractedData.forEach((orderId, orderData) {
loadedOrders.add(
OrderItem(
id: orderId,
amount: orderData['amount'],
dateTime: DateTime.parse(orderData['dateTime']),
products: (orderData['products'] as List<dynamic>)
.map(
(item) => CartItem(
id: item['id'],
price: item['price'],
quantity: item['quantity'],
title: item['title'],
),
)
.toList(),
),
);
});
_orders = loadedOrders.reversed.toList();
notifyListeners();
}
Future<void> addOrder(List<CartItem> cartProducts, double total) async {
final url = Uri.https(
'fluttershopapp-e471e-default-rtdb.firebaseio.com', '/orders.json');
final timestamp = DateTime.now();
final response = await http.post(
url,
body: json.encode({
'amount': total,
'dateTime': timestamp.toIso8601String(),
'products': cartProducts
.map((cp) => {
'id': cp.id,
'title': cp.title,
'quantity': cp.quantity,
'price': cp.price,
})
.toList(),
}),
);
_orders.insert(
0,
OrderItem(
id: json.decode(response.body)['name'],
amount: total,
dateTime: timestamp,
products: cartProducts,
),
);
notifyListeners();
}
}