Menu
CoddyTech

쇼핑 카트: 장바구니에 담기

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

이제 실제 공유 상태 앱인 작은 상점을 만들어 볼 시간입니다. 다음 강의들에서 상품 목록과 추가 버튼, 장바구니 아이콘의 배지, 합계가 표시되는 장바구니 화면, 상품을 삭제하는 방법과 결제 기능을 추가합니다. 화면은 두 개, 장바구니는 하나입니다.

장바구니는 공유 상태이므로 Notifier를 사용합니다. 장바구니의 상태는 장바구니에 담긴 상품 목록이며, 처음에는 비어 있습니다. 배운 것처럼 변경할 때마다 새 목록을 설정합니다.

class Cart extends Notifier<List<Product>> {
  @override
  List<Product> build() => [];

  void add(Product product) {
    state = [...state, product];
  }
}

상품 목록 자체는 절대 바뀌지 않으므로 파일 맨 위에 일반 const 목록으로 둡니다. 바뀌는 항목에만 프로바이더가 필요합니다.

challenge icon

챌린지

중급

추가 버튼을 눌러 장바구니를 채우세요:

  • 상태가 처음에는 비어 있는 List<Product>인 Cart 알림자를 작성하고, add(Product product) 메서드를 추가하세요.
  • final cartProvider = NotifierProvider<Cart, List<Product>>(Cart.new);를 추가하세요.
  • 각 행의 버튼을 누르면 해당 상품이 추가됩니다.
  • 상단 바에는 장바구니에 담긴 상품 수가 표시됩니다: Shop (0), Shop (1)...

직접 해보기

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),
];

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) {
    return Scaffold(
      appBar: AppBar(title: const Text('Shop')),
      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: () {},
              ),
            ),
        ],
      ),
    );
  }
}
quiz icon실력 점검

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

상태 관리의 모든 레슨

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