Counter for every item

Viewed 69

I am trying to make a cart page using the provider package and i wanted to have a quantity of every single item so every time i add a new product i want it to check if it exists in the list and if it exists i want it to count how many times it is added but if its not already in the cart it gets added to the cart

this is my Cart class

import 'package:flutter/material.dart';

import 'item.dart';

class Cart extends ChangeNotifier{
  List<Item> items = [];
  double totalPrice = 0.0;
  int singleProductCount = 0;

  void add(Item item) {
      items.add(item);
      totalPrice += item.price;
      notifyListeners();
  }

  void remove(Item item) {
    items.remove(item);
    totalPrice -= item.price;
    notifyListeners();
  }

  int get count {
    return items.length;
  }

  double get totalprice {
    return totalPrice;
  }

  int get singleproductCount {
    return singleProductCount;
  }

  List<Item> get basketItems {
    return items;
  }
}

and this is the IconButton that adds it to the cart

IconButton(icon: Icon(Icons.add), onPressed: () {
                                  cart.add(Item(name: snapshot.data.documents[index]["name"], price: snapshot.data.documents[index]["price"], imageUrl: snapshot.data.documents[index]["imageUrl"]));
                                }),
1 Answers

I have come up with a way, but hopefully, someone will have a better solution. But what I did was actually create another list to help us with the condition. This list will hold the names(or whatever you'd like it to hold). I then check if that name is in the list and if it is then it returns null, else add the Item into the list. This was the only way I could think of at the moment in the case when it comes to adding a class instance.

List<String> _names = [];
double totalPrice = 0.0;


List<String> get names {
  return _names;
  }



void add(Item item, String newNames) {
    itemList.add(item);
    _names.add(newNames); // add new names to names list
    totalPrice += item.price;
    notifyListeners();
  }
  // If the names list contains any name from the docs already, then don't add anything
  // else add the name to the list along with the Item
       cart.names.contains(snapshot.data.documents[index]["name"])
       ? null
       : cart.add(
        Item(
         name: snapshot.data.documents[index]["name"], 
         price: snapshot.data.documents[index]["price"],
         imageUrl: snapshot.data.documents[index]["imageUrl"]
        ),

         snapshot.data.documents[index]["name"]
     );

By the way, using get does not really make sense if you are not going to make your properties private by using an underscore, for example, int _singleProductCount = 0;

Related