Menu
CoddyTech

Warenkorb: Zur Kasse

Teil des Abschnitts State Management der Flutter-Journey von Coddy. Lektion 27 von 27.

Der letzte Baustein ist der Bezahlvorgang. Ein Tippen bewirkt drei Dinge: Der Warenkorb wird geleert, eine Nachricht bestätigt die Bestellung und der Käufer ist wieder im Shop, wo das Abzeichen verschwunden ist.

Das Leeren ist eine weitere Methode des Notifiers und setzt eine neue, leere Liste:

void clear() {
  state = [];
}

Ein Bezahlvorgang mit leerem Warenkorb ergibt keinen Sinn, also deaktiviere die Schaltfläche. Eine Schaltfläche, deren onPressed auf null gesetzt ist, kann nicht gedrückt werden:

onPressed: cart.isEmpty ? null : () { ... },

Sieh dir an, was du erstellt hast: zwei Bildschirme, ein Abzeichen und eine Gesamtsumme, die alle denselben Warenkorb auslesen, ohne dass ein Wert von Bildschirm zu Bildschirm weitergegeben wird. Das ist Zustandsverwaltung.

challenge icon

Aufgabe

Mittel

Füge unterhalb der Gesamtsumme auf dem Warenkorb-Bildschirm eine Schaltfläche Check out hinzu:

  • Ausgegraut, solange der Warenkorb leer ist.
  • Beim Drücken leert sie den Warenkorb mithilfe einer neuen Methode clear(), zeigt eine SnackBar mit der Meldung Order placed! an und kehrt zum Shop zurück.

Probier es selbst

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];
  }

  void removeAt(int index) {
    final copy = [...state];
    copy.removeAt(index);
    state = copy;
  }
}

final cartProvider = NotifierProvider<Cart, List<Product>>(Cart.new);

final totalProvider = Provider((ref) {
  final cart = ref.watch(cartProvider);
  return cart.fold(0.0, (sum, product) => sum + product.price);
});

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);
    final total = ref.watch(totalProvider);
    return Scaffold(
      appBar: AppBar(title: const Text('Your cart')),
      bottomNavigationBar: Padding(
        padding: const EdgeInsets.all(24),
        child: Text(
          'Total: \$${total.toStringAsFixed(2)}',
          style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
        ),
      ),
      body: cart.isEmpty
          ? const Center(child: Text('Your cart is empty'))
          : ListView(
              children: [
                for (var i = 0; i < cart.length; i++)
                  ListTile(
                    title: Text(cart[i].name),
                    subtitle: Text('\$${cart[i].price.toStringAsFixed(2)}'),
                    trailing: IconButton(
                      icon: const Icon(Icons.delete),
                      onPressed: () {
                        ref.read(cartProvider.notifier).removeAt(i);
                      },
                    ),
                  ),
              ],
            ),
    );
  }
}
quiz iconTeste dich selbst

Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.

Alle Lektionen in State Management

Übe selbstständig: Online-Flutter-Compiler