From 67d31493cf52beeccada22ae21d69ddee064df8b Mon Sep 17 00:00:00 2001 From: Moe Poi ~ Date: Fri, 10 Nov 2023 11:20:58 +0700 Subject: [PATCH] Use Hive for save cart data --- lib/data/cart.dart | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/lib/data/cart.dart b/lib/data/cart.dart index 718931a..c51619e 100644 --- a/lib/data/cart.dart +++ b/lib/data/cart.dart @@ -1,28 +1,25 @@ import 'dart:convert'; -import 'package:shared_preferences/shared_preferences.dart'; +import 'package:hive/hive.dart'; Future 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(); if (filteredCart.length == 0) { - cart.add({ - "product_id": productId, - "quantity": 1 - }); + cart.add({"product_id": productId, "quantity": 1}); } else { filteredCart[0]["quantity"]++; cart = cart.where((x) => x["product_id"] != productId).toList(); cart.add(filteredCart[0]); } - await prefs.setString('cart', jsonEncode(cart).toString()); + box.put('cart', jsonEncode(cart).toString()); } Future 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(); if (filteredCart.length > 0) { if (batch) { @@ -37,12 +34,12 @@ Future removeFromCart(productId, bool batch) async { } } } - await prefs.setString('cart', jsonEncode(cart).toString()); + box.put('cart', jsonEncode(cart).toString()); } Future 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; -} \ No newline at end of file +}