import 'package:flutter/foundation.dart'; import '../models/product_model.dart'; import '../models/cart_item_model.dart'; class CartService extends ChangeNotifier { static final CartService _instance = CartService._internal(); factory CartService() => _instance; CartService._internal(); final List _items = []; List get items => List.unmodifiable(_items); int get itemCount => _items.fold(0, (sum, item) => sum + item.quantity); int get uniqueItemCount => _items.length; double get totalPrice => _items.fold(0.0, (sum, item) => sum + item.subtotal); void addItem(Product product) { final index = _items.indexWhere((item) => item.product.id == product.id); if (index != -1) { _items[index].quantity++; } else { _items.add(CartItem(product: product, quantity: 1)); } notifyListeners(); } void removeItem(String productId) { final index = _items.indexWhere((item) => item.product.id == productId); if (index != -1) { if (_items[index].quantity > 1) { _items[index].quantity--; } else { _items.removeAt(index); } notifyListeners(); } } void removeAllOfProduct(String productId) { _items.removeWhere((item) => item.product.id == productId); notifyListeners(); } void clearCart() { _items.clear(); notifyListeners(); } }