How to Add Items to Cart Using SharedPreferences in Flutter
Introduction
In modern mobile applications, cart functionality is essential for e-commerce apps, grocery delivery, and other shopping-related platforms. In Flutter, we can use SharedPreferences to store cart items locally on the user’s device. This approach is useful for small-scale applications where a database isn’t required.
With SharedPreferences, we can store cart data persistently, ensuring users don’t lose their cart items when they close the app. This tutorial will guide you through the process of adding products to a cart, retrieving them, and displaying them in a Flutter UI. We’ll also cover how to clear the cart when needed.
By the end of this tutorial, you will learn how to:
- Store cart items in
SharedPreferences - Retrieve and display cart items in a
ListView - Remove all items from the cart
Let’s get started with the implementation.
Implementation
Step 1: Add Dependencies
First, include the shared_preferences package in your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.2.2
Step 2: Create a Cart Item Model
class CartItem {
String name;
double price;
int quantity;
CartItem({required this.name, required this.price, required this.quantity});
Map<String, dynamic> toJson() {
return {'name': name, 'price': price, 'quantity': quantity};
}
factory CartItem.fromJson(Map<String, dynamic> json) {
return CartItem(
name: json['name'],
price: json['price'],
quantity: json['quantity'],
);
}
}
Step 3: Implement Cart Service Using SharedPreferences
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'cart_item.dart';
class CartService {
static const String _cartKey = 'cart_items';
static Future<void> addToCart(CartItem item) async {
final prefs = await SharedPreferences.getInstance();
List<String> cartList = prefs.getStringList(_cartKey) ?? [];
cartList.add(jsonEncode(item.toJson()));
await prefs.setStringList(_cartKey, cartList);
}
static Future<List<CartItem>> getCartItems() async {
final prefs = await SharedPreferences.getInstance();
List<String> cartList = prefs.getStringList(_cartKey) ?? [];
return cartList.map((item) => CartItem.fromJson(jsonDecode(item))).toList();
}
static Future<void> clearCart() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_cartKey);
}
}
Step 4: Build the UI for Cart Management
import 'package:flutter/material.dart';
import 'cart_item.dart';
import 'cart_service.dart';
class CartPage extends StatefulWidget {
@override
_CartPageState createState() => _CartPageState();
}
class _CartPageState extends State<CartPage> {
List<CartItem> cartItems = [];
@override
void initState() {
super.initState();
loadCart();
}
Future<void> loadCart() async {
List<CartItem> items = await CartService.getCartItems();
setState(() {
cartItems = items;
});
}
Future<void> addItem() async {
CartItem newItem = CartItem(name: 'Product 1', price: 20.0, quantity: 1);
await CartService.addToCart(newItem);
loadCart();
}
Future<void> clearCart() async {
await CartService.clearCart();
loadCart();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Shopping Cart')),
body: Column(
children: [
ElevatedButton(onPressed: addItem, child: Text('Add Item')),
ElevatedButton(onPressed: clearCart, child: Text('Clear Cart')),
Expanded(
child: ListView.builder(
itemCount: cartItems.length,
itemBuilder: (context, index) {
final item = cartItems[index];
return ListTile(
title: Text(item.name),
subtitle: Text('₹${item.price} x ${item.quantity}'),
);
},
),
),
],
),
);
}
}
Code with Update Quanity
import ‘dart:convert’;
import ‘package:flutter/material.dart’;
import ‘package:shared_preferences/shared_preferences.dart’;
class CartItem {
String name;
double price;
int quantity;
CartItem({required this.name, required this.price, required this.quantity});
Map<String, dynamic> toJson() {
return {‘name’: name, ‘price’: price, ‘quantity’: quantity};
}
factory CartItem.fromJson(Map<String, dynamic> json) {
return CartItem(
name: json[‘name’],
price: json[‘price’],
quantity: json[‘quantity’],
);
}
}
class CartService {
static const String _cartKey = ‘cart_items’;
static Future<void> addToCart(CartItem item) async {
final prefs = await SharedPreferences.getInstance();
List<String> cartList = prefs.getStringList(_cartKey) ?? [];
List<CartItem> items = cartList.map((e) => CartItem.fromJson(jsonDecode(e))).toList();
int index = items.indexWhere((element) => element.name == item.name);
if (index != -1) {
items[index].quantity += item.quantity;
} else {
items.add(item);
}
await prefs.setStringList(_cartKey, items.map((e) => jsonEncode(e.toJson())).toList());
}
static Future<List<CartItem>> getCartItems() async {
final prefs = await SharedPreferences.getInstance();
List<String> cartList = prefs.getStringList(_cartKey) ?? [];
return cartList.map((item) => CartItem.fromJson(jsonDecode(item))).toList();
}
static Future<void> updateQuantity(String name, int quantity) async {
final prefs = await SharedPreferences.getInstance();
List<String> cartList = prefs.getStringList(_cartKey) ?? [];
List<CartItem> items = cartList.map((e) => CartItem.fromJson(jsonDecode(e))).toList();
int index = items.indexWhere((item) => item.name == name);
if (index != -1) {
items[index].quantity = quantity;
await prefs.setStringList(_cartKey, items.map((e) => jsonEncode(e.toJson())).toList());
}
}
static Future<void> deleteItem(String name) async {
final prefs = await SharedPreferences.getInstance();
List<String> cartList = prefs.getStringList(_cartKey) ?? [];
List<CartItem> items = cartList.map((e) => CartItem.fromJson(jsonDecode(e))).toList();
items.removeWhere((item) => item.name == name);
await prefs.setStringList(_cartKey, items.map((e) => jsonEncode(e.toJson())).toList());
}
static Future<void> clearCart() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_cartKey);
}
}
class CartPage extends StatefulWidget {
@override
_CartPageState createState() => _CartPageState();
}
class _CartPageState extends State<CartPage> {
List<CartItem> cartItems = [];
@override
void initState() {
super.initState();
loadCart();
}
Future<void> loadCart() async {
List<CartItem> items = await CartService.getCartItems();
setState(() {
cartItems = items;
});
}
Future<void> addItem() async {
CartItem newItem = CartItem(name: ‘Product 1’, price: 20.0, quantity: 1);
await CartService.addToCart(newItem);
loadCart();
}
Future<void> clearCart() async {
await CartService.clearCart();
loadCart();
}
Future<void> updateQuantity(int index, int newQuantity) async {
if (newQuantity > 0) {
await CartService.updateQuantity(cartItems[index].name, newQuantity);
loadCart();
}
}
Future<void> deleteItem(int index) async {
await CartService.deleteItem(cartItems[index].name);
loadCart();
}
double calculateGrandTotal() {
return cartItems.fold(0, (sum, item) => sum + (item.price * item.quantity));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(‘Shopping Cart’)),
body: Column(
children: [
ElevatedButton(onPressed: addItem, child: Text(‘Add Item’)),
ElevatedButton(onPressed: clearCart, child: Text(‘Clear Cart’)),
Expanded(
child: ListView.builder(
itemCount: cartItems.length,
itemBuilder: (context, index) {
final item = cartItems[index];
return ListTile(
title: Text(item.name),
subtitle: Text(‘₹${item.price} x ${item.quantity} = ₹${(item.price * item.quantity).toStringAsFixed(2)}’),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: Icon(Icons.remove),
onPressed: () => updateQuantity(index, item.quantity – 1),
),
Text(‘${item.quantity}’),
IconButton(
icon: Icon(Icons.add),
onPressed: () => updateQuantity(index, item.quantity + 1),
),
IconButton(
icon: Icon(Icons.delete),
onPressed: () => deleteItem(index),
),
],
),
);
},
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
‘Grand Total: ₹${calculateGrandTotal().toStringAsFixed(2)}’,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
),
],
),
);
}
}
Summary
In this tutorial, we implemented a simple cart system in Flutter using SharedPreferences. We covered how to:
- Create a
CartItemmodel to store product details. - Use
SharedPreferencesto store and retrieve cart items. - Display cart items dynamically in a list.
- Provide options to add and clear items from the cart.
This approach is ideal for small apps that do not require a backend. However, for larger applications, using a database like Firebase or SQLite would be a better solution. Happy coding!
