Files
flutter_ecommerce_portal/lib/services/cart_service.dart
rbhat 39a4f3283f Initialize project and update portal port configuration
Set default portal port to 8081, fix Dart build issue in cart screen, and update setup documentation.

Co-Authored-By: Oz <oz-agent@warp.dev>
2026-04-10 19:08:30 +05:30

44 lines
1.1 KiB
Dart

import 'package:flutter/foundation.dart';
import '../models/cart_item.dart';
import '../models/product.dart';
class CartService extends ChangeNotifier {
final List<CartItem> _items = [];
List<CartItem> get items => List.unmodifiable(_items);
int get totalItems => _items.fold(0, (sum, item) => sum + item.quantity);
double get totalPrice =>
_items.fold(0.0, (sum, item) => sum + item.lineTotal);
void addProduct(Product product) {
final index = _items.indexWhere((item) => item.product.id == product.id);
if (index == -1) {
_items.add(CartItem(product: product));
} else {
_items[index].quantity += 1;
}
notifyListeners();
}
void removeProduct(String productId) {
_items.removeWhere((item) => item.product.id == productId);
notifyListeners();
}
void updateQuantity(String productId, int quantity) {
if (quantity < 1) return;
final index = _items.indexWhere((item) => item.product.id == productId);
if (index == -1) return;
_items[index].quantity = quantity;
notifyListeners();
}
void clear() {
_items.clear();
notifyListeners();
}
}