Home > front end >  How to change only the number of the clicked widget in a list view in flutter
How to change only the number of the clicked widget in a list view in flutter

Time:11-08

I'm trying to build a shopping app. and when pressing this button this will increase and decrease the count.

enter image description here

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).

enter image description here

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();
  }
}
  • Related