Menu
CoddyTech

Alışveriş Sepeti: Sepet Ekranı

Coddy'nin Flutter Journey'sinin Durum Yönetimi bölümünün bir parçası. Ders 24 / 27.

İkinci ekran sepette neler olduğunu gösterir. Aynı cartProvider'ı izleyen bir ConsumerWidget'tır; bu nedenle ona herhangi bir şey aktarılması gerekmez: ekranı yığına ekleyin, sepeti kendisi okur.

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'un etrafında bulunan ve yığına eklenen bir ekrandan erişilemeyen sağlayıcıyı hatırlıyor musunuz? Burada böyle bir sorun yaşanamaz: ProviderScope tüm uygulamayı sardığından her ekran tüm sağlayıcılara erişebilir.

Ekrandaki boş bir liste bozuk görünür; bu nedenle onun yerine bir cümle gösterin: cart.isEmpty ? ... : ... iki seçenek arasında seçim yapar.

challenge icon

Görev

Orta

Alışveriş sepeti ekranını oluştur:

  • Başlığı Your cart olan bir CartScreen ConsumerWidget ekle.
  • Sepetteki her ürünü, adı ve trailing olarak fiyatı gösterilen bir ListTile şeklinde listeler.
  • Sepet boş olduğunda bunun yerine Your cart is empty gösterir.
  • Mağazanın üst çubuğundaki sepet simgesi bu ekranı açar.

Kendin dene

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 iconKendini test et

Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.

Durum Yönetimi bölümündeki tüm dersler

Kendi başına pratik yap: Online Flutter derleyicisi