Shopping Cart: The Cart Screen
Part of the State Management section of Coddy's Flutter journey. Lesson 24 of 27.
A second screen shows what is in the cart. It is a ConsumerWidget that watches the same cartProvider, so it needs nothing passed to it: push it, and it reads the cart itself.
class CartScreen extends ConsumerWidget {
const CartScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final cart = ref.watch(cartProvider);
return Scaffold(
appBar: AppBar(title: const Text('Your cart')),
body: ...,
);
}
}Remember the provider that sat around home and could not be found from a pushed screen? That cannot happen here: the ProviderScope wraps the whole app, so every screen reaches every provider.
An empty list on a screen looks broken, so show a sentence instead: cart.isEmpty ? ... : ... picks between the two.
Challenge
MediumBuild the cart screen:
- Add a
CartScreenConsumerWidgetwith the titleYour cart. - It lists each product in the cart as a
ListTilewith the name, and the price astrailing. - When the cart is empty, it shows
Your cart is emptyinstead. - The cart icon in the shop's top bar pushes it.
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),
];
class Cart extends Notifier<List<Product>> {
@override
List<Product> build() => [];
void add(Product product) {
state = [...state, product];
}
}
final cartProvider = NotifierProvider<Cart, List<Product>>(Cart.new);
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) {
final cart = ref.watch(cartProvider);
return Scaffold(
appBar: AppBar(
title: const Text('Shop'),
actions: [
IconButton(
icon: Badge(
label: Text('${cart.length}'),
isLabelVisible: cart.isNotEmpty,
child: const Icon(Icons.shopping_cart),
),
onPressed: () {},
),
],
),
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: () {
ref.read(cartProvider.notifier).add(product);
},
),
),
],
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in State Management
2Dart for Models
Methods on Your ClassesGetters in Your ClassesKeep a Field PrivateAdd Up a List With fold5Project: Shopping Cart
Shopping Cart: Add to CartShopping Cart: The BadgePractice on your own: Online Flutter compiler