쇼핑 카트: 총액
Coddy Flutter 여정의 상태 관리 섹션에 포함된 레슨. 27개 중 25번째.
장바구니 화면에는 합계가 필요합니다. 합계는 새로운 데이터가 아니라 장바구니에 담긴 항목을 바탕으로 계산됩니다. 따라서 어디에도 저장되지 않습니다. 장바구니를 감시하고 fold를 사용해 가격을 모두 더하는 프로바이더입니다.
final totalProvider = Provider((ref) {
final cart = ref.watch(cartProvider);
return cart.fold(0.0, (sum, product) => sum + product.price);
});장바구니를 감시하므로 장바구니가 변경될 때마다 합계를 다시 계산하고, 합계를 감시하는 모든 위젯에 새 금액이 표시됩니다.
목록 아래에 표시하세요. Scaffold의 bottomNavigationBar 슬롯에는 어떤 위젯이든 넣을 수 있으며, 목록이 스크롤되더라도 화면 맨 아래, 목록 아래에 유지됩니다.
챌린지
중급장바구니 화면에 총액을 표시하세요:
cartProvider를 감시하고 가격을 합산하는totalProvider를 추가하세요.- 장바구니 화면의
Scaffold에서bottomNavigationBar에 적당한 패딩을 적용해Total: $2.75(소수점 이하 두 자리)를 표시하세요.
직접 해보기
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);
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);
return Scaffold(
appBar: AppBar(title: const Text('Your cart')),
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 컴파일러