This repository was archived by the owner on Apr 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_cart.dart
More file actions
88 lines (85 loc) · 2.46 KB
/
api_cart.dart
File metadata and controls
88 lines (85 loc) · 2.46 KB
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
// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:my_app/API/api_login.dart';
import 'package:my_app/Providers/user_provider.dart';
import 'package:my_app/models/cart_model.dart';
import 'package:http/http.dart' as http;
import 'package:my_app/utils/constant.dart';
import 'package:my_app/utils/snackbar.dart';
import 'package:provider/provider.dart';
class CartApi {
Future<CartModel> getCart(BuildContext context) async {
CartModel cartModel = CartModel(
id: '',
userId: '',
cartCountProduct: 1,
product: [],
cartState: '',
);
try {
var userProvider = Provider.of<UserProvider>(context, listen: false);
String accessToken = userProvider.user.accessToken;
if (accessToken.isEmpty) {
var newAccessToken = await AuthLogin.getAccessToken();
accessToken = newAccessToken!;
}
http.Response res = await http.get(
Uri.parse('${uri}carts'),
headers: {
'Authorization': 'Bearer $accessToken',
},
);
httpErrorHandle(
response: res,
context: context,
onSuccess: () async {
String jsonRes = res.body;
dynamic decodeData = jsonDecode(jsonRes);
cartModel = CartModel.fromMap(decodeData);
},
);
} catch (e) {
showSnackBarError(context, e.toString());
}
return cartModel;
}
Future updateCart({
required BuildContext context,
required String productId,
required String sku,
required int quantity,
}) async {
try {
var userProvider = Provider.of<UserProvider>(context, listen: false);
String accessToken = userProvider.user.accessToken;
if (accessToken.isEmpty) {
final newAccessToken = await AuthLogin.getAccessToken();
accessToken = newAccessToken!;
}
http.Response res = await http.post(
Uri.parse('${uri}carts'),
body: jsonEncode(
{
'productId': productId,
'sku': sku,
'quantity': quantity,
},
),
headers: {
'Authorization': 'Bearer $accessToken',
'Content-Type': 'application/json; charset=UTF-8',
},
);
httpErrorHandle(
response: res,
context: context,
onSuccess: () async {
getCart(context);
},
);
} catch (e) {
showSnackBarError(context, e.toString());
}
}
}