Issue
i'm currently developing an e-commerce app,
i'm trying to increase the quantity of items the user are trying to shop and then show them in the "items Cart" but instead, i get multiple times the same item.
here's the code i'm using for it:
FlatButton(
onPressed: () {
_addToCart(context, this.widget.product);
},
textColor: Colors.redAccent,
child: Row(
children: [
Text('Add to Cart'),
IconButton(
icon: Icon(Icons.shopping_cart), onPressed: () {}),
],
),
),
_addToCart(BuildContext context, Product product) async {
var result = await _cartService.addToCart(product);
if (result > 0) {
print(result);
_showSnackMessage(Text(
'Item added to cart successfully!',
style: TextStyle(color: Colors.green),
));
} else {
_showSnackMessage(Text(
'Failed to add to cart!',
style: TextStyle(color: Colors.red),
));
}
}
addToCart(Product product) async {
List<Map> items =
await _repository.getLocalByCondition('carts', 'productId', product.id);
if (items.length > 0) {
product.quantity = items.first['productQuantity'] + 1;
return await _repository.updateLocal(
'carts', 'productId', product.toMap());
}
print(items);
product.quantity = 1;
return await _repository.saveLocal('carts', product.toMap());
}
Have anyone has experience something like this? Can anyone help me?
Solution
What are you using to keep your items? Local database or just a list? In any case you need to check your items contains first, then if it is you need update only quantity if it is not you need to add as a new element. I mean as I understand you check this with items.length > 0
and it looks too general, items.contains('productId')
would be more specific to use.
Answered By - Lunedor
Answer Checked By - Senaida (JavaFixing Volunteer)