Add addToCart function
This commit is contained in:
parent
a13987ea14
commit
7c4f9bea4b
1 changed files with 20 additions and 0 deletions
20
lib/data/cart.dart
Normal file
20
lib/data/cart.dart
Normal file
|
@ -0,0 +1,20 @@
|
|||
import 'dart:convert';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Future<void> addToCart(productId) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
|
||||
var cart = jsonDecode(prefs.getString('cart') ?? '[]');
|
||||
var filteredCart = cart.where((x) => x["product_id"] == productId).toList();
|
||||
if (filteredCart.length == 0) {
|
||||
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());
|
||||
}
|
Loading…
Add table
Reference in a new issue