购物车:角标
本课属于 Coddy Flutter 学习旅程的“状态管理”单元。第 23 课,共 27 课。
商店会用一个带小数字的图标来显示购物车,这个数字叫作徽标。Flutter 提供了一个对应的组件:Badge 会在其 child 的角落绘制一个红色气泡,并在其中显示 label:
IconButton(
icon: Badge(
label: Text('${cart.length}'),
isLabelVisible: cart.isNotEmpty,
child: const Icon(Icons.shopping_cart),
),
onPressed: () {},
)当 isLabelVisible 为 false 时,气泡会隐藏。购物车为空时会显示普通图标,这比显示 0 更简洁。列表中至少有一件商品时,cart.isNotEmpty 的值为 true。
这个徽标会监听和标题相同的 cartProvider。任何组件都可以这样做,无论它位于哪里。
挑战
简单将数量从标题移到徽章中:
- 将标题改回
Shop。 - 在顶部栏的
actions中添加一个购物车IconButton,并在Badge中放入Icons.shopping_cart,以显示商品数量。 - 购物车为空时,隐藏徽章中的数字。
这个按钮目前还没有功能;接下来会添加购物车页面。
亲手试试
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: Text('Shop (${cart.length})')),
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 在线编译器