85 lines
1.9 KiB
Dart
85 lines
1.9 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
|
|
import '../entities/cart_item.dart';
|
|
import '../entities/product.dart';
|
|
|
|
abstract interface class CartRepository implements Listenable {
|
|
List<CartItem> get items;
|
|
|
|
int get itemCount;
|
|
|
|
int? get totalMinorUnits;
|
|
|
|
void addProduct(Product product);
|
|
|
|
void increaseQuantity(Product product);
|
|
|
|
void decreaseQuantity(Product product);
|
|
|
|
void removeProduct(Product product);
|
|
|
|
void clear();
|
|
}
|
|
|
|
class InMemoryCartRepository extends ChangeNotifier implements CartRepository {
|
|
final Map<String, CartItem> _items = {};
|
|
|
|
@override
|
|
List<CartItem> get items => List.unmodifiable(_items.values);
|
|
|
|
@override
|
|
int get itemCount =>
|
|
_items.values.fold(0, (count, item) => count + item.quantity);
|
|
|
|
@override
|
|
int? get totalMinorUnits {
|
|
if (_items.values.any((item) => item.product.priceMinorUnits == null)) {
|
|
return null;
|
|
}
|
|
return _items.values.fold<int>(
|
|
0,
|
|
(total, item) => total + item.product.priceMinorUnits! * item.quantity,
|
|
);
|
|
}
|
|
|
|
@override
|
|
void addProduct(Product product) {
|
|
increaseQuantity(product);
|
|
}
|
|
|
|
@override
|
|
void increaseQuantity(Product product) {
|
|
final key = product.cartKey;
|
|
final existing = _items[key];
|
|
_items[key] = CartItem(
|
|
product: product,
|
|
quantity: (existing?.quantity ?? 0) + 1,
|
|
);
|
|
notifyListeners();
|
|
}
|
|
|
|
@override
|
|
void decreaseQuantity(Product product) {
|
|
final key = product.cartKey;
|
|
final existing = _items[key];
|
|
if (existing == null || existing.quantity <= 1) return;
|
|
_items[key] = CartItem(
|
|
product: existing.product,
|
|
quantity: existing.quantity - 1,
|
|
);
|
|
notifyListeners();
|
|
}
|
|
|
|
@override
|
|
void removeProduct(Product product) {
|
|
if (_items.remove(product.cartKey) != null) notifyListeners();
|
|
}
|
|
|
|
@override
|
|
void clear() {
|
|
if (_items.isEmpty) return;
|
|
_items.clear();
|
|
notifyListeners();
|
|
}
|
|
}
|