Use Hive for save cart data
This commit is contained in:
parent
016649ece6
commit
67d31493cf
1 changed files with 11 additions and 14 deletions
|
@ -1,28 +1,25 @@
|
|||
import 'dart:convert';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:hive/hive.dart';
|
||||
|
||||
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();
|
||||
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<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();
|
||||
if (filteredCart.length > 0) {
|
||||
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 {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final box = Hive.box();
|
||||
|
||||
var cart = jsonDecode(prefs.getString('cart') ?? '[]');
|
||||
var cart = jsonDecode(box.get('cart', defaultValue: '[]'));
|
||||
return cart;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue