Menu
CoddyTech

쇼핑 카트: 장바구니 화면

Coddy Flutter 여정의 상태 관리 섹션에 포함된 레슨. 27개 중 24번째.

두 번째 화면에는 장바구니에 담긴 항목이 표시됩니다. 이 화면은 같은 cartProvider를 감시하는 ConsumerWidget이므로 전달받을 것이 없습니다. 화면을 push하면 장바구니를 직접 읽습니다.

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: ...,
    );
  }
}

home을 둘러싸고 있어서 push된 화면에서는 찾을 수 없었던 provider를 기억하나요? 여기서는 그런 일이 일어나지 않습니다. ProviderScope가 앱 전체를 감싸므로 모든 화면에서 모든 provider에 접근할 수 있습니다.

화면에 빈 목록만 표시되면 문제가 있는 것처럼 보이므로 대신 문장을 표시하세요. cart.isEmpty ? ... : ...가 둘 중 하나를 선택합니다.

challenge icon

챌린지

중급

장바구니 화면을 만드세요:

  • Your cart라는 제목을 가진 CartScreen ConsumerWidget을 추가하세요.
  • 장바구니의 각 상품을 이름과 가격을 trailing으로 표시하는 ListTile로 나열하세요.
  • 장바구니가 비어 있으면 대신 Your cart is empty를 표시하세요.
  • 상점 상단 표시줄의 장바구니 아이콘을 누르면 장바구니 화면으로 이동합니다.

직접 해보기

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: () {},
          ),
        ],
      ),
      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);
                },
              ),
            ),
        ],
      ),
    );
  }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

상태 관리의 모든 레슨

직접 연습해 보세요: 온라인 Flutter 컴파일러