...

/

Solution: Implementing the Shopping Cart

Solution: Implementing the Shopping Cart

View the solution of implementing the shopping cart functionality.

We hope you did well in the exercise! It’s time to compare your solution to ours.

Implementing ShoppingCartCubit

To implement the ShoppingCartCubit, we can use the functions provided to us by the ShoppingCart model.

Press + to interact
// inside lib\cubits\shopping_cart\shopping_cart_cubit.dart
void addItemToCart(ShoppingCartItem item) {
ShoppingCart updatedCart = state.shoppingCart.copyWith();
updatedCart.addItem(item);
emit(ShoppingCartUpdated(updatedCart));
}
void removeItemFromCart(ShoppingCartItem item) {
ShoppingCart updatedCart = state.shoppingCart.copyWith();
updatedCart.removeItem(item);
emit(ShoppingCartUpdated(updatedCart));
}
void clearCart() {
ShoppingCart updatedCart = state.shoppingCart.copyWith();
updatedCart.clear();
emit(ShoppingCartUpdated(updatedCart));
}

In all of these functions, we use the respective functions provided to us in the ShoppingCart model. Therefore, for addItemToCart(), we use the addItem() function (line 4); for removeItemFromCart(), we use the removeItem() function (line 10); and for clearCart(), we use the clear() function (line 16). ...

Access this course and 1400+ top-rated courses and projects.