Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 73 ยท Projects

Project: Shopping App with Cart and Navigation

Build a Flutter shopping app: a product grid, a detail page with a Hero image, cart state with ChangeNotifier, go_router navigation and a validated checkout form.

A shop is the classic test of everything you have learned so far. It has a scrolling catalog, a detail screen you reach by tapping an item, state that lives across screens (the cart), and a form at the end. In this project you design each piece, read the real Flutter code, and then run stand-ins that prove the logic works.

You will not write much new theory here. Instead you connect the ideas from lists and grids, Hero transitions, Provider, go_router and forms into one app.

Real vs stand-in. All Dart and widget code below is real Flutter and is read-only, because the site has no Dart runtime. The live examples are JavaScript stand-ins for the logic: a cart model with listeners, a router that matches paths, and a validator pipeline. They behave like their Flutter counterparts, but they are not Flutter.

Four screens

Catalog A grid of products.
Detail One product with a Hero image.
Cart Lines, quantities, total.
Checkout A validated form.
1 / 2

Step 1: the model

Keep the data plain. A product is immutable, and money is stored in cents as an integer so you never add 0.1 + 0.2.

DART
class Product {
  const Product({
    required this.id,
    required this.name,
    required this.priceCents,
    required this.color,
  });

  final String id;
  final String name;
  final int priceCents;
  final Color color;
}

String formatPrice(int cents) => '\$${(cents / 100).toStringAsFixed(2)}';

The \$ is an escaped dollar sign, because $ starts interpolation in Dart strings. A real app would load products with the techniques from HTTP requests and JSON; here a const list is enough.

Step 2: cart state

The cart is shared by the catalog (a badge), the detail page (an "Add" button), the cart page and checkout. That makes it app state, so it lives above the router. A ChangeNotifier is enough:

DART
class Cart extends ChangeNotifier {
  final Map<String, int> _quantities = {};

  int get itemCount => _quantities.values.fold(0, (a, b) => a + b);

  int quantityOf(String productId) => _quantities[productId] ?? 0;

  void add(Product p) {
    _quantities.update(p.id, (q) => q + 1, ifAbsent: () => 1);
    notifyListeners();
  }

  void remove(Product p) {
    final q = quantityOf(p.id);
    if (q <= 1) {
      _quantities.remove(p.id);
    } else {
      _quantities[p.id] = q - 1;
    }
    notifyListeners();
  }

  int totalCents(List<Product> catalog) => catalog.fold(
        0,
        (sum, p) => sum + p.priceCents * quantityOf(p.id),
      );

  void clear() {
    _quantities.clear();
    notifyListeners();
  }
}

The map stores ids and counts, not copies of products, so there is one source of truth for names and prices. Every mutation calls notifyListeners(); forgetting it is the number one reason a cart badge does not update.

Provide the cart once, above MaterialApp.router:

DART
void main() {
  runApp(
    ChangeNotifierProvider(
      create: (_) => Cart(),
      child: const ShopApp(),
    ),
  );
}

Try the cart logic

This stand-in is the same class in JavaScript, with a tiny listener list in place of ChangeNotifier.

JS Stand-in: cart with listeners

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each call prints the new badge count, which is exactly what a Consumer or context.watch<Cart>() would rebuild with.

Step 3: the router

A shop has real URLs on the web and deep links on mobile, so use go_router. The catalog is /, a product is /product/:id, then /cart and /checkout:

DART
final router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => const CatalogPage(),
      routes: [
        GoRoute(
          path: 'product/:id',
          builder: (context, state) {
            final product = findProduct(state.pathParameters['id']!);
            return ProductPage(product: product);
          },
        ),
      ],
    ),
    GoRoute(path: '/cart', builder: (context, state) => const CartPage()),
    GoRoute(path: '/checkout', builder: (context, state) => const CheckoutPage()),
  ],
);

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: router,
      theme: ThemeData(colorSchemeSeed: Colors.indigo),
    );
  }
}

Navigate with context.push('/product/mug') when you want a back button (the product stacks on the catalog), and context.go('/cart') when you are jumping to a place. The product is a nested route, so deep-linking to /product/mug still produces a stack with the catalog below it. See declarative routing for the details.

A good habit: if an id is unknown, show a "not found" page instead of crashing on !. GoRouter also takes an errorBuilder for unmatched paths.

Try the route matcher

JS Stand-in: match paths and build a stack

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that /product/mug yields a two-page stack. That is the nested-route behavior the real package gives you, which is why the back button always has somewhere to go.

Step 4: the catalog grid

A GridView.builder builds only the cells that are visible, which keeps long catalogs smooth. The cell count adapts to width with SliverGridDelegateWithMaxCrossAxisExtent:

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

  @override
  Widget build(BuildContext context) {
    final itemCount = context.select<Cart, int>((c) => c.itemCount);
    return Scaffold(
      appBar: AppBar(
        title: const Text('Shop'),
        actions: [
          IconButton(
            onPressed: () => context.push('/cart'),
            icon: Badge.count(
              count: itemCount,
              isLabelVisible: itemCount > 0,
              child: const Icon(Icons.shopping_cart_outlined),
            ),
          ),
        ],
      ),
      body: GridView.builder(
        padding: const EdgeInsets.all(12),
        gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: 220,
          mainAxisSpacing: 12,
          crossAxisSpacing: 12,
          childAspectRatio: 0.8,
        ),
        itemCount: products.length,
        itemBuilder: (context, i) => ProductCard(product: products[i]),
      ),
    );
  }
}

context.select rebuilds the page only when the count changes, not on every cart change. That matters more as the page grows.

Step 5: product detail with a Hero

The card and the detail page share a Hero with the same tag. The tag must be unique on each page, so use the product id:

DART
// In ProductCard
InkWell(
  onTap: () => context.push('/product/${product.id}'),
  child: Column(
    children: [
      Expanded(
        child: Hero(
          tag: 'product-${product.id}',
          child: ColoredBox(color: product.color),
        ),
      ),
      ListTile(title: Text(product.name), subtitle: Text(formatPrice(product.priceCents))),
    ],
  ),
)

// In ProductPage
Hero(
  tag: 'product-${product.id}',
  child: Container(height: 280, color: product.color),
)

The "Add to cart" button calls context.read<Cart>().add(product). Use read, not watch, inside callbacks: you want to run an action, not subscribe.

Step 6: cart and checkout

The cart page lists the lines with + and โˆ’ buttons and a total. Because it needs the catalog to turn ids into products, it filters the catalog by quantityOf(p.id) > 0.

The checkout page is a Form with a key, which lets one call validate every field:

DART
class _CheckoutPageState extends State<CheckoutPage> {
  final _formKey = GlobalKey<FormState>();
  final _email = TextEditingController();
  final _postcode = TextEditingController();

  @override
  void dispose() {
    _email.dispose();
    _postcode.dispose();
    super.dispose();
  }

  void _submit() {
    if (!_formKey.currentState!.validate()) return;
    context.read<Cart>().clear();
    context.go('/');
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('Order placed')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Checkout')),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            TextFormField(
              controller: _email,
              keyboardType: TextInputType.emailAddress,
              decoration: const InputDecoration(labelText: 'Email'),
              validator: (v) =>
                  (v == null || !v.contains('@')) ? 'Enter a valid email' : null,
            ),
            TextFormField(
              controller: _postcode,
              decoration: const InputDecoration(labelText: 'Postcode'),
              validator: (v) =>
                  (v == null || v.trim().length < 4) ? 'At least 4 characters' : null,
            ),
            const SizedBox(height: 24),
            FilledButton(onPressed: _submit, child: const Text('Place order')),
          ],
        ),
      ),
    );
  }
}

Two details matter. The controllers are disposed, and the snackbar is shown right after context.go, using a context that is still mounted in the same synchronous call. If you ever add an await before them, check if (!mounted) return; first (see common mistakes).

Try the validator pipeline

JS Stand-in: validate fields like Form.validate()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Form.validate() does the same: it runs every field's validator, shows each message, and returns true only when all return null.

Ideas to extend it

  • Load products from an API and show loading and error states (FutureBuilder).
  • Persist the cart so it survives restarts (local storage).
  • Add a redirect that sends users with an empty cart away from /checkout.
  • Write a unit test for Cart.totalCents and a widget test for the badge.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the cart provided above MaterialApp.router instead of inside the catalog page?

    Pushed routes sit beside the catalog in the Navigator, not below it, so shared state must live above the router.
  2. 2. Which call fits an Add to cart button's onPressed?

    read runs an action without subscribing the widget to rebuilds; watch belongs in build.
  3. 3. Why store prices as integer cents?

    Integer cents make addition exact; format to dollars only when displaying.
  4. 4. What does the nested route 'product/:id' under '/' guarantee for a deep link?

    Nested routes build a stack of parent then child pages for the location.

Summary

  • Model products immutably, with prices in cents, and keep only ids and counts in the cart.
  • Shared state goes above the router; select limits rebuilds, read runs actions.
  • go_router gives URLs and deep links; nested routes build the stack for you.
  • A Form with a GlobalKey<FormState> validates all fields with one call.
  • Hero tags must match between the two pages and be unique on each.

Next: Project: A Simple 2D Game