Menu
CoddyTech

Shopping Cart: Add to Cart

Part of the State Management section of Coddy's Flutter journey. Lesson 22 of 27.

Time to build a real shared state app: a small shop. Over the next lessons it gets a product list with add buttons, a badge on the cart icon, a cart screen with a total, a way to remove items and a checkout. Two screens, one cart.

The cart is the shared state, so it gets a Notifier. Its state is the list of products in the cart, and it starts empty. Every change sets a new list, as you learned:

class Cart extends Notifier<List<Product>> {
  @override
  List<Product> build() => [];

  void add(Product product) {
    state = [...state, product];
  }
}

The product list itself never changes, so it stays a plain const list at the top of the file. Only what changes needs a provider.

challenge icon

Challenge

Medium

Make the add buttons fill a cart:

  • Write a Cart notifier whose state is a List<Product>, empty at the start, with an add(Product product) method.
  • Add final cartProvider = NotifierProvider<Cart, List<Product>>(Cart.new);
  • Each row's button adds its product.
  • The top bar shows the number of products in the cart: Shop (0), Shop (1)...

Try it yourself

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class Product {
  const Product(this.name, this.price);

  final String name;
  final double price;
}

const products = [
  Product('Apple', 0.5),
  Product('Bread', 2.25),
  Product('Cheese', 4),
  Product('Milk', 1.2),
];

void main() {
  runApp(const ProviderScope(child: MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: ShopPage(),
    );
  }
}

class ShopPage extends ConsumerWidget {
  const ShopPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      appBar: AppBar(title: const Text('Shop')),
      body: ListView(
        children: [
          for (final product in products)
            ListTile(
              title: Text(product.name),
              subtitle: Text('\$${product.price.toStringAsFixed(2)}'),
              trailing: IconButton(
                icon: const Icon(Icons.add_shopping_cart),
                onPressed: () {},
              ),
            ),
        ],
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in State Management

Practice on your own: Online Flutter compiler