Menu
CoddyTech

ショッピングカート:カートに追加

CoddyのFlutterジャーニー「状態管理」セクションの一部。レッスン 22/27。

実際に共有状態を使うアプリを作る時間です。小さなお店を作ります。これからのレッスンで、追加ボタン付きの商品一覧、カートアイコンのバッジ、合計金額が表示されるカート画面、商品を削除する方法、そしてチェックアウト機能を追加していきます。画面は2つ、カートは1つです。

カートは共有状態なので、Notifierを使います。その状態はカート内の商品一覧で、最初は空です。学んだとおり、変更のたびに新しいリストを設定します。

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

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

商品一覧自体は決して変わらないので、ファイルの先頭にある通常のconstリストのままにします。プロバイダーが必要なのは、変化するものだけです。

challenge icon

チャレンジ

中級

追加ボタンでカートに商品を入れましょう:

  • 状態が最初は空のList<Product>であるCartノティファイアを作成し、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オンラインコンパイラ