쇼핑 카트: 상품 삭제
Coddy Flutter 여정의 상태 관리 섹션에 포함된 레슨. 27개 중 26번째.
잘못된 상품을 담은 구매자가 되돌릴 수 있도록 장바구니의 각 행에 삭제 버튼이 필요합니다.
장바구니에는 같은 상품이 두 번 담길 수 있으므로, 상품이 아니라 위치를 기준으로 제거하세요. 앞서 배운 규칙은 여전히 유효합니다. 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)}'),
),
],
),
);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
상태 관리의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러