Reputation: 800
I have a variable that I'm using in my cart that I'm using to update the total. When I navigate to my cart page, all the variable are calculated properly. I then am allowing users to update the quantity in the cart but, whenever I do, it seems like the value is calculated multiple times over and I cannot understand where the bug is.
Initially, I call this function to get the total:
void getCartTotal() {
final cart = CartProvider.of(context);
if (cart.orderDetails != null) {
for (int i = 0; i < cart.orderDetails.length; i++) {
setState(() {
cartTotal +=
(cart.orderDetails[i].price * cart.orderDetails[i].quantity);
});
print('There are ${cart.orderDetails.length} many items in the cart');
minReached(cartTotal);
}
}
}
Then when updating the quantity in the cart, I use this counter:
Counter(
color: Colors.white,
textStyle: TextStyle(
fontFamily: 'Poppins',
color: buddiesPurple,
fontSize: screenAwareSize(15, context)),
buttonSize: screenAwareSize(20, context),
minValue: 1,
maxValue: 10,
step: 1,
decimalPlaces: 0,
initialValue: cart.orderDetails[i].quantity,
onChanged: (num val) {
setState(() {
cart.orderDetails[i].quantity = val;
getCartTotal();
});
},
),
But whenever I try to update the cart (Increasing or decreasing), the values just double. Any help would be appreciated
Upvotes: 0
Views: 2728
Reputation: 126734
I think that you need to reset your cartTotal
back to 0
before looping over your items and adding their values to the total:
void getCartTotal() {
final cart = CartProvider.of(context);
if (cart.orderDetails != null) {
cartTotal = 0;
for (int i = 0; i < cart.orderDetails.length; i++) {
setState(() {
cartTotal +=
(cart.orderDetails[i].price * cart.orderDetails[i].quantity);
});
print('There are ${cart.orderDetails.length} many items in the cart');
minReached(cartTotal);
}
}
}
See where it says cartTotal = 0
. If you do not do that, every time you increment a counter, the cartToal
will double plus the increment.
Upvotes: 1