ショッピングカート:商品を削除
CoddyのFlutterジャーニー「状態管理」セクションの一部。レッスン 26/27。
間違った商品を追加してしまった買い物客が戻れるように、カートの各行に削除ボタンを付けましょう。
カートには同じ商品を2回入れられるので、商品ではなく位置を指定して削除します。先ほどのルールは引き続き有効です。stateをその場で変更してはいけません。コピーを作り、そのコピーを変更して、新しい状態として設定します。
void removeAt(int index) {
final copy = [...state];
copy.removeAt(index);
state = copy;
}各行の位置を知るには、インデックスを使ってループします。for (var i = 0; i < cart.length; i++)を使い、その行の商品にはcart[i]を使います。
商品を削除して、残りの表示が連動して変わるのを確認しましょう。リスト、合計金額、そしてショップに戻ったときのバッジ。これらはすべて同じカートを参照しています。
チャレンジ
難しいカート画面で:
- そのアイテムを除いた新しいリストを設定する
removeAt(int index)メソッドをCartに追加します。 - 各行の価格を
subtitleに移動し、trailingをIcons.deleteを使ってその行を削除するIconButtonにします。
自分で試してみよう
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);
final totalProvider = Provider((ref) {
final cart = ref.watch(cartProvider);
return cart.fold(0.0, (sum, product) => sum + product.price);
});
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: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const CartScreen()),
);
},
),
],
),
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);
},
),
),
],
),
);
}
}
class CartScreen extends ConsumerWidget {
const CartScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final cart = ref.watch(cartProvider);
final total = ref.watch(totalProvider);
return Scaffold(
appBar: AppBar(title: const Text('Your cart')),
bottomNavigationBar: Padding(
padding: const EdgeInsets.all(24),
child: Text(
'Total: \$${total.toStringAsFixed(2)}',
style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
),
body: cart.isEmpty
? const Center(child: Text('Your cart is empty'))
: ListView(
children: [
for (final product in cart)
ListTile(
title: Text(product.name),
trailing: Text('\$${product.price.toStringAsFixed(2)}'),
),
],
),
);
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
状態管理のすべてのレッスン
5プロジェクト:ショッピングカート
ショッピングカート:カートに追加ショッピングカート:バッジ自分で練習してみよう: Flutterオンラインコンパイラ