Use Hive for save cart data

This commit is contained in:
Moe Poi ~ 2023-11-10 11:20:58 +07:00
parent 016649ece6
commit 67d31493cf

View file

@ -1,28 +1,25 @@
import 'dart:convert'; import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:hive/hive.dart';
Future<void> addToCart(productId) async { Future<void> addToCart(productId) async {
final prefs = await SharedPreferences.getInstance(); final box = Hive.box();
var cart = jsonDecode(prefs.getString('cart') ?? '[]'); var cart = jsonDecode(box.get('cart', defaultValue: '[]'));
var filteredCart = cart.where((x) => x["product_id"] == productId).toList(); var filteredCart = cart.where((x) => x["product_id"] == productId).toList();
if (filteredCart.length == 0) { if (filteredCart.length == 0) {
cart.add({ cart.add({"product_id": productId, "quantity": 1});
"product_id": productId,
"quantity": 1
});
} else { } else {
filteredCart[0]["quantity"]++; filteredCart[0]["quantity"]++;
cart = cart.where((x) => x["product_id"] != productId).toList(); cart = cart.where((x) => x["product_id"] != productId).toList();
cart.add(filteredCart[0]); cart.add(filteredCart[0]);
} }
await prefs.setString('cart', jsonEncode(cart).toString()); box.put('cart', jsonEncode(cart).toString());
} }
Future<void> removeFromCart(productId, bool batch) async { Future<void> removeFromCart(productId, bool batch) async {
final prefs = await SharedPreferences.getInstance(); final box = Hive.box();
var cart = jsonDecode(prefs.getString('cart') ?? '[]'); var cart = jsonDecode(box.get('cart', defaultValue: '[]'));
var filteredCart = cart.where((x) => x["product_id"] == productId).toList(); var filteredCart = cart.where((x) => x["product_id"] == productId).toList();
if (filteredCart.length > 0) { if (filteredCart.length > 0) {
if (batch) { if (batch) {
@ -37,12 +34,12 @@ Future<void> removeFromCart(productId, bool batch) async {
} }
} }
} }
await prefs.setString('cart', jsonEncode(cart).toString()); box.put('cart', jsonEncode(cart).toString());
} }
Future<dynamic> viewCart() async { Future<dynamic> viewCart() async {
final prefs = await SharedPreferences.getInstance(); final box = Hive.box();
var cart = jsonDecode(prefs.getString('cart') ?? '[]'); var cart = jsonDecode(box.get('cart', defaultValue: '[]'));
return cart; return cart;
} }