CarritoModel.dart 1.03 KB
Newer Older
nayeli92433 committed
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
import 'package:flutter/material.dart';
import '../models/ArticuloModel.dart';

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

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

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


  void addToCart(ArticleModel article) {
    final existingItemIndex = _carrito.indexWhere((item) => item.articulo.id == article.id);

    if (existingItemIndex >= 0) {
      // Si el artículo ya está en el carrito, aumenta la cantidad
      _carrito[existingItemIndex].cantidad += 1;
    } else {
      // Si el artículo no está en el carrito, agrégalo
      final newItem = CarritoModel(
        articulo: article,
        precio: article.precios.isNotEmpty ? article.precios.first.precio : 0.0,
      );
      _carrito.add(newItem);
    }

    notifyListeners();
  }

  int get totalCarrito {
    return _carrito.length;
  }

  List<CarritoModel> get carrito {
    return [..._carrito];
  }
}