Menu
CoddyTech

עגלת קניות: הוספה לעגלה

חלק מהיחידה ניהול מצב במסלול ה-Flutter של Coddy. שיעור 22 מתוך 27.

הגיע הזמן לבנות אפליקציה אמיתית עם מצב משותף: חנות קטנה. בשיעורים הבאים נוסיף לה רשימת מוצרים עם כפתורי הוספה, תג על סמל העגלה, מסך עגלה עם סכום כולל, אפשרות להסיר פריטים ואפשרות לתשלום. שני מסכים, עגלה אחת.

העגלה היא המצב המשותף, ולכן היא מקבלת Notifier. המצב שלה הוא רשימת המוצרים שבעגלה, והיא מתחילה ריקה. בכל שינוי מגדירים רשימה חדשה, כפי שלמדת:

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

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

רשימת המוצרים עצמה לעולם אינה משתנה, ולכן היא נשארת רשימת const רגילה בראש הקובץ. רק עבור מה שמשתנה צריך ספק.

challenge icon

אתגר

בינוני

גרמו ללחצני ההוספה למלא עגלת קניות:

  • כתבו notifier בשם Cart שהמצב שלו הוא List<Product>, ריק בתחילת הדרך, עם מתודה 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 אונליין