feat: add CartController for cart state management
This commit is contained in:
91
lib/src/controllers/cart_controller.dart
Normal file
91
lib/src/controllers/cart_controller.dart
Normal file
@@ -0,0 +1,91 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:mom_kitchen/src/controllers/base/base_controller.dart';
|
||||
import 'package:mom_kitchen/src/controllers/home_controller.dart';
|
||||
|
||||
class CartItem {
|
||||
final ProductModel product;
|
||||
int quantity;
|
||||
|
||||
CartItem({
|
||||
required this.product,
|
||||
this.quantity = 1,
|
||||
});
|
||||
|
||||
double get totalPrice => product.price * quantity;
|
||||
}
|
||||
|
||||
class CartController extends BaseController {
|
||||
final cartItems = <CartItem>[].obs;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
void addProduct(ProductModel product) {
|
||||
final index = cartItems.indexWhere((item) => item.product.name == product.name);
|
||||
if (index >= 0) {
|
||||
cartItems[index].quantity++;
|
||||
cartItems.refresh();
|
||||
} else {
|
||||
cartItems.add(CartItem(product: product));
|
||||
}
|
||||
}
|
||||
|
||||
void removeProduct(String productName) {
|
||||
cartItems.removeWhere((item) => item.product.name == productName);
|
||||
}
|
||||
|
||||
void updateQuantity(String productName, int quantity) {
|
||||
final index = cartItems.indexWhere((item) => item.product.name == productName);
|
||||
if (index >= 0) {
|
||||
if (quantity <= 0) {
|
||||
cartItems.removeAt(index);
|
||||
} else {
|
||||
cartItems[index].quantity = quantity;
|
||||
cartItems.refresh();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void incrementQuantity(String productName) {
|
||||
final index = cartItems.indexWhere((item) => item.product.name == productName);
|
||||
if (index >= 0) {
|
||||
cartItems[index].quantity++;
|
||||
cartItems.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
void decrementQuantity(String productName) {
|
||||
final index = cartItems.indexWhere((item) => item.product.name == productName);
|
||||
if (index >= 0) {
|
||||
if (cartItems[index].quantity > 1) {
|
||||
cartItems[index].quantity--;
|
||||
cartItems.refresh();
|
||||
} else {
|
||||
cartItems.removeAt(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void clearCart() {
|
||||
cartItems.clear();
|
||||
}
|
||||
|
||||
double get totalPrice {
|
||||
return cartItems.fold(0.0, (sum, item) => sum + item.totalPrice);
|
||||
}
|
||||
|
||||
int get totalItems {
|
||||
return cartItems.fold(0, (sum, item) => sum + item.quantity);
|
||||
}
|
||||
|
||||
bool isInCart(String productName) {
|
||||
return cartItems.any((item) => item.product.name == productName);
|
||||
}
|
||||
|
||||
int getQuantity(String productName) {
|
||||
final index = cartItems.indexWhere((item) => item.product.name == productName);
|
||||
return index >= 0 ? cartItems[index].quantity : 0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user