1
0
Fork 0
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
thesis_shop/lib/stores/cart_store.dart

82 lines
2.6 KiB

import 'package:flutter/material.dart';
import 'package:thesis_shop/models/cart_item.dart';
import 'package:thesis_shop/models/product.dart';
import 'package:thesis_shop/stores/product_store.dart';
class CartStoreImplementation extends StatefulWidget {
final Widget child;
const CartStoreImplementation({Key? key, required this.child})
: super(key: key);
@override
_CartStoreImplementationState createState() =>
_CartStoreImplementationState();
}
class _CartStoreImplementationState extends State<CartStoreImplementation> {
Map<ProductTitle, int> productAmounts = {};
void increaseAmount(Product product) => setState(() {
final currentAmount =
productAmounts.putIfAbsent(product.title, () => 0);
productAmounts[product.title] = currentAmount + 1;
});
void decreaseAmount(Product product) => setState(() {
final currentAmount =
productAmounts.putIfAbsent(product.title, () => 0);
productAmounts[product.title] =
currentAmount <= 0 ? 0 : currentAmount - 1;
});
@override
Widget build(BuildContext context) {
final products = ProductStore.of(context).productsOrNull ?? const [];
final productsByTitle = {
for (var product in products) product.title: product
};
final cartItems = productAmounts
.map((key, value) => MapEntry(productsByTitle[key], value))
.entries
.where((entry) => entry.key != null && entry.value > 0)
.map((entry) => CartItem(product: entry.key!, amount: entry.value))
.toList();
return CartStore(
cartItems: cartItems,
increaseAmount: increaseAmount,
decreaseAmount: decreaseAmount,
child: widget.child,
);
}
}
class CartStore extends InheritedWidget {
const CartStore({
Key? key,
required this.cartItems,
required this.increaseAmount,
required this.decreaseAmount,
required Widget child,
}) : super(key: key, child: child);
final List<CartItem> cartItems;
final Function(Product) increaseAmount;
final Function(Product) decreaseAmount;
int amountOfProduct(Product product) {
final amounts = {
for (final item in cartItems) item.product: item.amount,
};
return amounts.putIfAbsent(product, () => 0);
}
static CartStore of(BuildContext context) {
final CartStore? result =
context.dependOnInheritedWidgetOfExactType<CartStore>();
assert(result != null, 'No CartStore found in context');
return result!;
}
@override
bool updateShouldNotify(CartStore oldWidget) {
return cartItems != oldWidget.cartItems;
}
}