쇼핑 카트: 배지
Coddy Flutter 여정의 상태 관리 섹션에 포함된 레슨. 27개 중 23번째.
상점에서는 장바구니를 작은 숫자가 표시된 아이콘, 즉 배지로 보여 줍니다. Flutter에는 이를 위한 위젯이 있습니다. Badge는 child의 모서리에 있는 빨간 말풍선 안에 label을 표시합니다.
IconButton(
icon: Badge(
label: Text('${cart.length}'),
isLabelVisible: cart.isNotEmpty,
child: const Icon(Icons.shopping_cart),
),
onPressed: () {},
)isLabelVisible이 false이면 말풍선이 숨겨집니다. 장바구니가 비어 있으면 숫자 0이 표시되는 것보다 덜 부담스러운 기본 아이콘이 표시됩니다. 목록에 항목이 하나 이상 있으면 cart.isNotEmpty는 true입니다.
배지는 제목에서 사용한 것과 동일한 cartProvider를 감시합니다. 어떤 위젯이든 어디에 있든 그렇게 할 수 있습니다.
챌린지
쉬움개수를 제목에서 배지로 옮기세요:
- 제목을 다시
Shop으로 설정하세요. - 상단 표시줄의
actions에 장바구니IconButton을 추가하고, 그 안에 상품 개수를 표시하는Badge와Icons.shopping_cart을 넣으세요. - 장바구니가 비어 있을 때는 배지의 숫자를 숨기세요.
아직 이 버튼은 아무 동작도 하지 않습니다. 다음 단계에서 장바구니 화면을 만듭니다.
직접 해보기
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: Text('Shop (${cart.length})')),
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);
},
),
),
],
),
);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
상태 관리의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러