Advertisement
rafisbr

cart_provider.dart

Jul 13th, 2021
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:shamo/models/cart_model.dart';
  3. import 'package:shamo/models/product_model.dart';
  4.  
  5. class CartProvider with ChangeNotifier {
  6. List<CartModel> _carts = [];
  7.  
  8. List<CartModel> get carts => _carts;
  9.  
  10. set carts(List<CartModel> carts) {
  11. _carts = carts;
  12. notifyListeners();
  13. }
  14.  
  15. addCart(ProductModel product) {
  16. if (productExist(product)) {
  17. int index =
  18. _carts.indexWhere((element) => element.product.id == product.id);
  19. _carts[index].quantity++;
  20. } else {
  21. _carts.add(
  22. CartModel(
  23. id: _carts.length,
  24. product: product,
  25. quantity: 1,
  26. ),
  27. );
  28. }
  29.  
  30. notifyListeners();
  31. }
  32.  
  33. removeCart(int id) {
  34. _carts.removeAt(id);
  35. notifyListeners();
  36. }
  37.  
  38. addQuantity(int id) {
  39. _carts[id].quantity++;
  40. notifyListeners();
  41. }
  42.  
  43. reduceQuantity(int id) {
  44. _carts[id].quantity--;
  45. if (_carts[id].quantity == 0) {
  46. _carts.removeAt(id);
  47. }
  48. notifyListeners();
  49. }
  50.  
  51. totalItems() {
  52. int total = 0;
  53. for (var item in _carts) {
  54. total += item.quantity;
  55. }
  56. return total;
  57. }
  58.  
  59. totalPrice() {
  60. double total = 0;
  61. for (var item in _carts) {
  62. total += (item.quantity * item.product.price);
  63. }
  64. return total;
  65. }
  66.  
  67. productExist(ProductModel product) {
  68. if (_carts.indexWhere((element) => element.product.id == product.id) ==
  69. -1) {
  70. return false;
  71. } else {
  72. return true;
  73. }
  74. }
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement