I am creating a Cart screen where items added to cart are listed. I have a list of item tiles that has name, image, price and the number of item. The number of item has two buttons that increases and decreases the number. When I increase/decrease an item from the list. Other item tiles' number also gets updated.
My UI and changenotifier class code below.
UI CODE
SizedBox(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
IconButton(
icon: Icon(
Icons.remove_circle_outline,
color: context.color.primaryColor,
),
onPressed: () {
context.read<CartItemProvider>().dcrItem();
},
),
Text(
"${context.watch<CartItemProvider>().noOfItem}",
style: context.textTheme.displayLarge,
),
IconButton(
icon: Icon(
Icons.add_circle,
color: context.color.primaryColor,
),
onPressed: () {
context.read<CartItemProvider>().incItem();
},
),
],
),
)
Provider Class
class CartItemProvider extends ChangeNotifier {
int noOfItem = 1;
void incItem() {
noOfItem++;
notifyListeners();
}
void dcrItem() {
if (noOfItem == 1) return;
noOfItem--;
notifyListeners();
}
}
For this, you have two possible ways. The first way is to wrap the widget of each item/CartTile with its own provider and then find a way to retrieve that information when your cart is submitted. On the other hand, the second one is easier. In your cartItemProvider, you can have a list of items List = []; and when you want to update the item count, you can pass the item id and then update it.
I hope it helps! Regards.