2022-04-26 05:43:20 +02:00
|
|
|
import 'dart:convert';
|
2023-11-10 05:20:58 +01:00
|
|
|
import 'package:hive/hive.dart';
|
2022-04-26 05:43:20 +02:00
|
|
|
|
|
|
|
Future<void> addToCart(productId) async {
|
2023-11-10 05:20:58 +01:00
|
|
|
final box = Hive.box();
|
2022-04-26 05:43:20 +02:00
|
|
|
|
2023-11-10 05:20:58 +01:00
|
|
|
var cart = jsonDecode(box.get('cart', defaultValue: '[]'));
|
2022-04-26 05:43:20 +02:00
|
|
|
var filteredCart = cart.where((x) => x["product_id"] == productId).toList();
|
|
|
|
if (filteredCart.length == 0) {
|
2023-11-10 05:20:58 +01:00
|
|
|
cart.add({"product_id": productId, "quantity": 1});
|
2022-04-26 05:43:20 +02:00
|
|
|
} else {
|
|
|
|
filteredCart[0]["quantity"]++;
|
|
|
|
cart = cart.where((x) => x["product_id"] != productId).toList();
|
|
|
|
cart.add(filteredCart[0]);
|
|
|
|
}
|
2023-11-10 05:20:58 +01:00
|
|
|
box.put('cart', jsonEncode(cart).toString());
|
2022-04-26 05:44:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
Future<void> removeFromCart(productId, bool batch) async {
|
2023-11-10 05:20:58 +01:00
|
|
|
final box = Hive.box();
|
2022-04-26 05:44:42 +02:00
|
|
|
|
2023-11-10 05:20:58 +01:00
|
|
|
var cart = jsonDecode(box.get('cart', defaultValue: '[]'));
|
2022-04-26 05:44:42 +02:00
|
|
|
var filteredCart = cart.where((x) => x["product_id"] == productId).toList();
|
|
|
|
if (filteredCart.length > 0) {
|
|
|
|
if (batch) {
|
|
|
|
cart = cart.where((x) => x["product_id"] != productId).toList();
|
|
|
|
} else {
|
|
|
|
filteredCart[0]["quantity"]--;
|
|
|
|
if (filteredCart[0]["quantity"] == 0) {
|
|
|
|
cart = cart.where((x) => x["product_id"] != productId).toList();
|
|
|
|
} else {
|
|
|
|
cart = cart.where((x) => x["product_id"] != productId).toList();
|
|
|
|
cart.add(filteredCart[0]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-11-10 05:20:58 +01:00
|
|
|
box.put('cart', jsonEncode(cart).toString());
|
2022-04-26 05:45:04 +02:00
|
|
|
}
|
|
|
|
|
2022-04-26 05:55:30 +02:00
|
|
|
Future<dynamic> viewCart() async {
|
2023-11-10 05:20:58 +01:00
|
|
|
final box = Hive.box();
|
2022-04-26 05:45:04 +02:00
|
|
|
|
2023-11-10 05:20:58 +01:00
|
|
|
var cart = jsonDecode(box.get('cart', defaultValue: '[]'));
|
2022-04-26 05:45:04 +02:00
|
|
|
return cart;
|
2023-11-10 05:20:58 +01:00
|
|
|
}
|