쇼핑 카트: 결제하기
Coddy Flutter 여정의 상태 관리 섹션에 포함된 레슨. 27개 중 27번째.
마지막 부분은 결제입니다. 한 번 탭하면 세 가지 일이 일어납니다. 장바구니가 비워지고, 주문을 확인하는 메시지가 표시되며, 쇼핑객은 배지가 사라진 상점 화면으로 돌아갑니다.
비우기는 알림자에 추가되는 또 하나의 메서드이며, 새 빈 목록을 설정합니다.
void clear() {
state = [];
}장바구니에 아무것도 없는데 결제하는 것은 말이 되지 않으므로 버튼을 비활성화하세요. onPressed가 null인 버튼은 누를 수 없습니다.
onPressed: cart.isEmpty ? null : () { ... },지금까지 만든 것을 돌아보세요. 두 개의 화면, 배지와 합계가 모두 하나의 장바구니를 읽으며, 화면 간에 값이 전달되지 않습니다. 이것이 상태 관리입니다.
챌린지
중급장바구니 화면에서 합계 아래에 Check out 버튼을 추가하세요:
- 장바구니가 비어 있는 동안에는 비활성화됩니다.
- 누르면 새
clear()메서드를 사용해 장바구니를 비우고,Order placed!라고 표시된SnackBar를 보여 준 다음 상점으로 돌아갑니다.
직접 해보기
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];
}
void removeAt(int index) {
final copy = [...state];
copy.removeAt(index);
state = copy;
}
}
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 (var i = 0; i < cart.length; i++)
ListTile(
title: Text(cart[i].name),
subtitle: Text('\$${cart[i].price.toStringAsFixed(2)}'),
trailing: IconButton(
icon: const Icon(Icons.delete),
onPressed: () {
ref.read(cartProvider.notifier).removeAt(i);
},
),
),
],
),
);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
상태 관리의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러