Menu
CoddyTech

购物车:添加到购物车

本课属于 Coddy Flutter 学习旅程的“状态管理”单元。第 22 课,共 27 课。

现在来构建一个真正使用共享状态的应用:一家小商店。在接下来的几节课中,你会为它添加商品列表和添加按钮、购物车图标上的徽标、带总价的购物车页面、移除商品的方法,以及结账功能。两个页面,一个购物车。

购物车就是共享状态,因此它会使用一个 Notifier。它的状态是购物车中的商品列表,初始为空。每次更改都会设置一个新列表,就像你学过的那样:

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

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

商品列表本身不会改变,因此它可以保持为文件顶部的普通 const 列表。只有会发生变化的内容才需要 provider。

challenge icon

挑战

中等

让“添加”按钮把商品加入购物车:

  • 编写一个 Cart 通知器,其状态为 List<Product>,初始为空,并包含一个 add(Product product) 方法。
  • 添加 final cartProvider = NotifierProvider<Cart, List<Product>>(Cart.new);
  • 每一行的按钮都会添加对应的商品。
  • 顶部栏显示购物车中的商品数量:Shop (0)、Shop (1)……

亲手试试

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 icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

状态管理中的所有课

自己练习: Flutter 在线编译器