carrito_provider.dart 1.84 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
import 'package:flutter/material.dart';
import '../models/article_model.dart';

class CarritoModel {
  final ArticleModel articulo;
  int cantidad;
  double precio;

  CarritoModel({required this.articulo, required this.cantidad, required this.precio});
}

class CarritoProvider with ChangeNotifier {
  List<CarritoModel> _carrito = [];

  List<CarritoModel> get carrito => _carrito;

  void addToCart(ArticleModel article) {
    var existingItem = _carrito.firstWhere( // firstWhere busca un artículo en el carrito que tenga el mismo ID que el artículo
          (item) => item.articulo.id == article.id,
      orElse: () => CarritoModel(articulo: article, cantidad: 0, precio: 0),
    );

    if (existingItem.cantidad == 0) {
      CarritoModel item = CarritoModel(
        articulo: article,
        cantidad: 1,
        precio: article.precios[0].precio,
      );
      _carrito.add(item);
    } else {
      existingItem.cantidad += 1;
    }
    notifyListeners(); // esto nos notifica los widgets que escuchan cambios en el carrito de compras, hace que se actualicen y reflejen los cambios.
  }

  void removeFromCart(ArticleModel article) {
    _carrito.removeWhere((item) => item.articulo.id == article.id);
    notifyListeners();
  }

  void updateQuantity(ArticleModel article, int quantity) {
    var existingItem = _carrito.firstWhere(
          (item) => item.articulo.id == article.id,
      orElse: () => CarritoModel(articulo: article, cantidad: 0, precio: 0),
    );

    if (existingItem.cantidad != 0) {
      existingItem.cantidad = quantity;
      if (existingItem.cantidad <= 0) {
        removeFromCart(article);
      }
    }
    notifyListeners();
  }

  double get totalAmount => _carrito.fold(0.0, (total, current) => total + (current.precio * current.cantidad));

  int get totalItems => _carrito.fold(0, (total, current) => total + current.cantidad);
}