flutter - 通过在颤振中删除提供程序类中的重复条目来更新购物车
问题描述
我正在使用购物车应用程序并使用 flutter-Provider 更新我的购物车。一切正常,但我的购物车列表中出现重复项目,如何删除这些重复条目并添加数量。我想获取包含项目和数量的列表。请帮我处理这段代码,我可以在哪里添加逻辑并过滤列表中删除的重复项。
这是我的代码:
购物车列表.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();}
}
解决方案
我迭代购物车存储桶并检查 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]);
}
推荐阅读
- atom-editor - 升级到 MacOs Mojave 后 Xdebug 和 Atom 不起作用
- ios - 无法在 Mac 上运行适用于 iOS 的 Uno 项目 - 无法加载“SQLitePCLRaw.core”
- python - Python 3 unittest 补丁未返回所需值
- camera - Jetson Xavier 入门级 CSI-2 摄像头模块
- sql-server - SQL Server:每晚从文件中批量插入数据
- entity-framework - Entity Framework 6 DB First 方法,没有 EDMX。可能吗?
- php - 带有要转换为纯 HTML 的简码的 Wordpress 发布内容
- azure-active-directory - 如何设置检测另一个目录中的 AD 更改的 Azure 触发器?
- java - 事件线程和主线程的代码结构
- f# - F# / FAKE - 如何在调用 MSBuild 时指定 `--platform:x64`