Menu
CoddyTech

Warenkorb: Der Gesamtbetrag

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

Der Warenkorb-Bildschirm benötigt einen Gesamtbetrag. Der Gesamtbetrag ist kein neuer Wert: Er ergibt sich aus dem Inhalt des Warenkorbs. Deshalb wird er nirgends gespeichert. Es handelt sich um einen Provider, der den Warenkorb beobachtet und die Preise mit fold addiert:

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

Da er den Warenkorb beobachtet, wird der Gesamtbetrag bei jeder Änderung des Warenkorbs neu berechnet, und jedes Widget, das den Gesamtbetrag beobachtet, zeigt den neuen Betrag an.

Zeige ihn unter der Liste an. Der Slot bottomNavigationBar eines Scaffold nimmt ein beliebiges Widget auf und hält es am unteren Bildschirmrand unter der Liste, selbst wenn die Liste scrollt.

challenge icon

Aufgabe

Mittel

Zeige die Gesamtsumme auf dem Warenkorb-Bildschirm an:

  • Füge einen totalProvider hinzu, der cartProvider beobachtet und die Preise addiert.
  • Zeige auf dem Warenkorb-Bildschirm Total: $2.75 (mit zwei Dezimalstellen) in der bottomNavigationBar des Scaffold mit etwas Innenabstand an.

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

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: () {
              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);
    return Scaffold(
      appBar: AppBar(title: const Text('Your cart')),
      body: cart.isEmpty
          ? const Center(child: Text('Your cart is empty'))
          : ListView(
              children: [
                for (final product in cart)
                  ListTile(
                    title: Text(product.name),
                    trailing: Text('\$${product.price.toStringAsFixed(2)}'),
                  ),
              ],
            ),
    );
  }
}
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