This image show List of Added items in the CartList, pressing the "--" or "+" does not reflect on the UI This second image shows the quantity of the same Item after I manually rebuild the UI**Say I have two Lists: ** List of Products from API List A []; Empty CartList where products from List A above can be added to CartList once and increment the quantity if it has already existed in the CartList; Example 1: List of items from the API [productA, productB, productC....]; 2. Add an element from a list in 1 above if it does not exist in CartList before:- CartList = [productA]; 3. If it already exist in CartList increase the quantity only and make it Single instance in the CartList like this: CartList = [productA(1),productB(5)...]; This code works fine but it doesn't update the UI except if I leave the page and open it again which not what I want. This is the code below:
//This Code add the product to the CartList
Consumer(
builder: (BuildContext context, WidgetRef ref, Widget? child) {
return DefaultButton(
onTap: () {
ref.read(cartProvider.notifier).addToCart(product);
context.pushRoute(
const MyCartScreen(),
);
},
text: "Add to cart",
);
},
),
//This increase the count quantity of the product in the CartList
AddRemoveWidget(
count: "$productCount",
productDecrement: () {
ref
.read(cartProvider.notifier)
.removeFromCart(index);
},
productIncrement: () {
ref
.read(cartProvider.notifier)
.addToCart(
cartItems[index].product!);
},
),
//This the StateNotifier
class CartList extends StateNotifier<List<CartItemModel>> {
CartList() : super([]);
//Add Product to Cart
void addToCart(Product product) {
// check it product is int the list
final isInList = state
.where((element) => element.product!.sId == product.sId).isNotEmpty;
if (isInList) {
final p =
state.where((element) => element.product!.sId == product.sId).first;
p.quantity += 1;
// final count = state.where((element) => element.product!.sId == product.sId).length;
// final p = state.where((element) => element.product!.sId == product.sId).first;
// p.quantity = count;
final index = state.indexOf(p);
final items = state;
items[index] = p;
state = items;
} else {
state = [...state, CartItemModel(product: product)];
}
}
void removeFromCart(int index) {
// check it product is int the list
final item = state[index];
if (item.quantity == 1) {
// remove it from the list of cart items
state = state
.where((element) => element.product!.sId != item.product!.sId)
.toList();
} else {
item.quantity -= 1;
state[index] = item;
}
}
}
final cartProvider = StateNotifierProvider<CartList, List<CartItemModel>>(
(ref) => CartList(),
);