I'm trying to build a shopping app. and when pressing this button this will increase and decrease the count.
here is the code (I'm using the provider package)
ListView.separated(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
itemCount: categoryList[index].dishCategory.length,
itemBuilder: (context, i) {
final data = categoryList[index].dishCategory[i];
return DishDetailsWidget(
data: data,
onAdd: () {
provider.increment();
},
onRemove: () {
provider.decrement();
},
);
},
separatorBuilder: (context, index) =>
const Divider(height: 5),
)
here is the provider code
class CartProvider extends ChangeNotifier {
int counter = 0;
increment() {
counter ;
notifyListeners();
}
decrement() {
if (counter == 0) {
counter;
} else {
counter--;
}
notifyListeners();
}
}
but it is adding the whole button data (as it should be per the code).
how do I make increment only the button that I press?
CodePudding user response:
The problem is that you're storing just a single counter value in your provider.
You need your provider to store the counter for every item separately.
In the map, for example, like this:
class CartProvider extends ChangeNotifier {
Map<int, int> counter = {};
increment(int id) {
counter[id] = counter[id] == null ? 1 : counter[id] 1;
notifyListeners();
}
decrement(int id) {
if (counter[id] > 0) {
counter[id] -= 1;
}
notifyListeners();
}
}