Exercise: Implementing the Shopping Cart

Test your Flutter BLoC skills by implementing the shopping cart feature in the e-commerce application.

We'll cover the following

In this exercise, implement the ShoppingCartCubit and use it in the code. The states of the ShoppingCartCubit are already created for you. Here are the states available to be used:

  • ShoppingCartInitial: This represents the initial state of ShoppingCartCubit, which is the state that the ShoppingCartCubit will be in when it’s first created.

  • ShoppingCartUpdated: This represents the state of the ShoppingCartCubit that will be emitted when the shopping cart is updated, either by adding items or removing items from the cart.

Both of these states extend the ShoppingCartState abstract class. We can find these states and the values they track in lib\cubits\shopping_cart\shopping_cart_state.dart

Problem statement

To implement the shopping cart feature, we need to implement three methods in the ShoppingCartCubit: addItemToCart(), removeItemFromCart(), and clearCart(). These methods can be implemented in lib\cubits\shopping_cart\shopping_cart_cubit.dart

After successfully implementing these functions, we can move on to adding the shopping cart logic to the rest of the app:

  • Inside lib\main.dart: Provide the ShoppingCartCubit to the app.

  • Inside lib\screens\cart_screen\cart_screen.dart: Get the list of items inside the shopping cart.

  • Inside lib\screens\cart_screen\widgets\cart_screen_appbar.dart: Implement the clear cart functionality.

  • Inside lib\screens\cart_screen\widgets\checkout_button.dart: Show the total price of the cart.

  • Inside lib\screens\item_screen\widgets\item_screen_cart_button.dart and lib\widgets\add_to_cart_button.dart: Implement the add to cart functionality.

  • Inside lib\widgets\remove_from_cart.dart: Implement the remove from cart functionality.

Code

Note: Upon application execution, you can visit the URL after “Your app can be found at:” to view the app. 

Get hands-on with 1200+ tech skills courses.