购物车:页面
本课属于 Coddy Flutter 学习旅程的“状态管理”单元。第 24 课,共 27 课。
第二个屏幕会显示购物车中的内容。它是一个会监听同一个 cartProvider 的 ConsumerWidget,所以不需要向它传入任何内容:将它推入导航栈,它就会自行读取购物车。
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: ...,
);
}
}还记得那个包裹在 home 周围、从推入的屏幕中无法找到的 provider 吗?这里不会发生这种情况:ProviderScope 包裹着整个应用,因此每个屏幕都能访问每个 provider。
屏幕上显示空列表看起来像是坏了,所以改为显示一句话:cart.isEmpty ? ... : ... 会在两者之间进行选择。
挑战
中等构建购物车页面:
- 添加一个
CartScreenConsumerWidget,标题为Your cart。 - 将购物车中的每件商品列为一个
ListTile,显示商品名称,并将价格设为trailing。 - 购物车为空时,则显示
Your cart is empty。 - 点击商店顶部栏中的购物车图标可打开该页面。
亲手试试
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);
},
),
),
],
),
);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
状态管理中的所有课
自己练习: Flutter 在线编译器