我正在使用购物车应用程序,并使用flutter-Provider更新我的购物车。一切正常,但我的购物车列表中有重复的物品,如何删除这些重复的条目并增加数量。我想获得包含物品和数量的清单。请通过这段代码为我提供帮助,在哪里可以添加逻辑并过滤出已删除重复项的列表。
这是我的代码:
CartList.dart:
class CartList extends ChangeNotifier{
List<CategoryItems> cartList = [];
double _totalPrice = 0.0;
addCartItem(CategoryItems categoryItems){
cartList.add(categoryItems);
categoryItems.Counter++;
_totalPrice+=double.parse(categoryItems.OurPrice);
notifyListeners();
}
removeCartItem(CategoryItems categoryItems){
_totalPrice-=double.parse(categoryItems.OurPrice);
categoryItems.Counter--;
if(categoryItems.Counter<1){
categoryItems.ShouldVisible = false;
}
cartList.remove(categoryItems);
notifyListeners();
}
int get count{
return cartList.length;
}
double get totalPrice{
return _totalPrice;
}
List<CategoryItems> get basketItem{
return cartList;
}
incrementCounter(CategoryItems categoryItems){
categoryItems.Counter++;
notifyListeners();
}
decrementCounter(CategoryItems categoryItems)
{
categoryItems.Counter--;
notifyListeners();
}
}
CategoryItem.dart:
class CategoryItems{
String CategoryName;
int Counter;
String MarketPrice;
String Name;
String OurPrice;
bool ShouldVisible;
String TotalDiscount;
String Weight;
int ID;
String get getCategoryName => CategoryName;
int get getCounter => Counter;
String get getMarketPrice => MarketPrice;
String get getName => Name;
String get getOurPrice => OurPrice;
bool get getShouldVisible => ShouldVisible;
String get getTotalDiscount => TotalDiscount;
String get getWeight => Weight;
int get getID => ID;
CategoryItems(
this.CategoryName,
this.Counter,
this.MarketPrice,
this.Name,
this.OurPrice,
this.ShouldVisible,
this.TotalDiscount,
this.Weight,
this.ID
);
}
这里我使用了包含:
addCartItem(CategoryItems categoryItems){
if(cartList.contains(categoryItems.ID)){
categoryItems.Counter++;
_totalPrice+=double.parse(categoryItems.OurPrice);
}else{
cartList.add(categoryItems);
categoryItems.Counter++;
_totalPrice+=double.parse(categoryItems.OurPrice);
notifyListeners();}
}
答案 0 :(得分:0)
我迭代购物车存储桶并通过以下方式检查ontap中的冗余值:
bool itemFound = false;
for(var i=0;i<CART.count;i++)
{
if(CART.count>=1 && categoryItemList[index].ID==CART.basketItem[i].ID){
itemFound = true;
break;
}else{
print('Item Not Exists');
}
}
if(itemFound == true){
print(itemFound);
CART.addQuantityOnly(categoryItemList[index]);
}else{
print(itemFound);
CART.addCartItem(categoryItemList[index]);
}