Menu
CoddyTech

Warenkorb: In den Warenkorb legen

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

Jetzt wird eine echte App mit gemeinsamem Zustand erstellt: ein kleiner Laden. In den nächsten Lektionen bekommt sie eine Produktliste mit Hinzufügen-Schaltflächen, ein Abzeichen am Warenkorb-Symbol, eine Warenkorbansicht mit einer Gesamtsumme, eine Möglichkeit, Artikel zu entfernen, und einen Checkout. Zwei Bildschirme, ein Warenkorb.

Der Warenkorb ist der gemeinsame Zustand und bekommt daher einen Notifier. Sein Zustand ist die Liste der Produkte im Warenkorb, und er ist anfangs leer. Jede Änderung setzt eine neue Liste, wie du gelernt hast:

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

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

Die Produktliste selbst ändert sich nie und bleibt daher eine einfache const-Liste am Anfang der Datei. Nur für das, was sich ändert, wird ein Provider benötigt.

challenge icon

Aufgabe

Mittel

Lass die Hinzufügen-Schaltflächen einen Warenkorb füllen:

  • Schreibe einen Cart-Notifier, dessen Zustand eine List<Product> ist, die anfangs leer ist, mit einer add(Product product)-Methode.
  • Füge final cartProvider = NotifierProvider<Cart, List<Product>>(Cart.new); hinzu.
  • Die Schaltfläche jeder Zeile fügt das jeweilige Produkt hinzu.
  • Die obere Leiste zeigt die Anzahl der Produkte im Warenkorb an: Shop (0), Shop (1)...

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

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 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