How to use the flutter_cart package?

Osama Asif
4 min readMar 17, 2024

Hi folks, Today we are going to learn how to use the Flutter cart package for maintaining your shopping cart šŸ›’

What is flutter_cart package?

The Flutter Cart Package is a versatile and robust package designed to manage shopping carts effectively within Flutter applications. It provides developers with a set of tools and utilities to handle cart functionalities, including adding items to the cart, updating item quantities, applying discounts, and persisting cart data locally.

Key Features:

  1. Cart Management: The package allows developers to easily add items to the cart, update item quantities, and remove items from the cart.
  2. Persistent Storage: With built-in support for persistent storage using the shared_preferences plugin, cart data can be stored locally on the userā€™s device, ensuring that the cart remains intact even after the app is closed or the user logs out.
  3. Discount Management: Developers can apply discounts to specific items in the cart, providing flexibility in pricing strategies and promotional campaigns.
  4. Flexibility: The package is highly customizable, allowing developers to tailor cart functionalities to meet the specific requirements of their e-commerce applications.

Step 1:

Letā€™s start with installing the flutter cart dependency in your applicationšŸ˜ƒ

dependencies:
flutter:
sdk: flutter
flutter_cart:

Run flutter pub get to install the package.

Step 2:

Initialize the Flutter Cart Package in your application, specifying whether to enable persistent storage support:

   // Set [isPersistenceSupportEnabled] to true to turn on the cart persistence
void main() async {
WidgetsFlutterBinding.ensureInitialized();
var cart = FlutterCart();
await cart.initializeCart(isPersistenceSupportEnabled: true);
runApp(MyApp());
}

Step 3:

Use the addToCart method to add items to the cart:

     // This method is called when we have to add an item to the cart
// Example:
void addToCart(YourProductModel product) {
flutterCart.addToCart(
cartModel: CartModel(
// ... other parameters
if [discount] is applicable and in percentage so, you can
calculate the discount like this
var discount = (product.discountPercentage / 100) * product.price;
discount: discount,
[productMeta] takes Map<String, dynamic> so, you can store your complete product data in productMeta
productMeta: product.toJson()),
);
}

Step 4:

Utilize the updateQuantity method to increment or decrement item quantities:

    // [updateQuantity] is used to increment/decrement the item quantity
// Example:
void updateQuantity(CartModel item, int newQuantity) {
flutterCart.updateQuantity(
item.productId, item.variants, newQuantity);
}

Step 5:

Use the removeItem method to remove specific items from the cart:

    // [removeItem] is used for removing the specific item from the cart
// Example:
void removeItemFromCart(CartModel item) {
flutterCart.removeItem(item.productId, item.variants);
}

Hereā€™s the complete code for the better understanding:

In this example, Iā€™m using Riverpod for the state management you can use any state management tools like Bloc, Providers, etc.

import 'package:flutter/material.dart';
import 'package:flutter_cart/flutter_cart.dart';
import 'package:example/models/products_model.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final cartNotifierProvider = ChangeNotifierProvider<CartNotifier>((ref) {
return CartNotifier();
});

class CartNotifier extends ChangeNotifier {
var flutterCart = FlutterCart();

void addToCart(ProductItemsModel product) {
var discount = (product.discountPercentage / 100) * product.price;
flutterCart.addToCart(
cartModel: CartModel(
productId: product.id.toString(),
productName: product.title,
variants: [
ProductVariant(price: product.price),
],
productDetails: product.description,
discount: discount,
productMeta: product.toJson()),
);
notifyListeners();
}

void updateQuantity(CartModel item, int newQuantity) {
flutterCart.updateQuantity(
item.productId.toString(), item.variants, newQuantity);
notifyListeners();
}

void removeItemFromCart(CartModel item) {
flutterCart.removeItem(item.productId.toString(), item.variants);
notifyListeners();
}

void clearCart() {
flutterCart.clearCart();
notifyListeners();
}

int get getCartCount => flutterCart.cartLength;
List<CartModel> get getCartItems => flutterCart.cartItemsList;
double get getTotalAmount => flutterCart.total;
double get subtotal => flutterCart.subtotal;
}

Conclusion

The Flutter Cart Package simplifies cart management in Flutter applications, offering a comprehensive set of tools and utilities for developers to streamline e-commerce development. By enabling features such as persistent storage, discount management, and flexible customization options, the package empowers developers to build robust and user-friendly shopping experiences for their customers.

With its ease of use and versatility, the Flutter Cart Package is a valuable asset for Flutter developers seeking to enhance the functionality and efficiency of their e-commerce applications. By integrating the package into their projects, developers can accelerate development processes, reduce complexity, and deliver exceptional shopping experiences to their users.

Overall, the Flutter Cart Package exemplifies the power of Flutterā€™s ecosystem in facilitating rapid and efficient application development, making it a must-have tool for e-commerce app developers leveraging the Flutter framework.

Working example

GitHub Repo šŸ‘‡

Hurrayā€¦!!!šŸ„³šŸ„³šŸ„³

These are the basic steps for implementing the flutter_cart package in your application. If you like it, support me by giving šŸ‘ and follow me here and on Github to show some love šŸ˜‰

--

--

Osama Asif

Seasoned software engineer with over 6 years of extensive industry experience specializing in the development of mobile applications.