Search code examples
flutterdartprovider

flutter lists and provider how to increase an int value in the list?


I'm using a Listview.builder to build a list of buttons based on information from a list which is housed in a change notifier. here is an example of the items contained in the list:

ListItem(cost1: 2, cost2: 0, canSelect: 1, timesChosen: 0, name: 'Item 1'),

and here is an example of the object (button) that is being built in the listview.builder:

ListView.builder(
                  itemBuilder: (context, index) {
                    return InkWell(
                      onTap: () {
                        context.read<MyProvider>().MyList[index].timesChosen++;
                      },
                      child: EquipmentButton(
                          text: context.read<MyProvider>().MyList[index].name,
                          Cost1: '${context.read<MyProvider>().MyList[index].cost1}',
                          timesChosen: '${context.read<MyProvider>().MyList[index].timesChosen}',
                     ),
                    );
                  },
                  itemCount: context.read<MyProvider>().MyList.length),

when I run this code, It builds the buttons correctly. but when a button is pressed, I get the below error: Class 'ListItem' has no instance setter 'timesChosen='. Receiver: Instance of 'ListItem' Tried calling: timesChosen=1

How do i get it to increase the value of timesChosen in the list?

thanks so much,


Solution

  • figured it out. just had to add a void function in the Listitem class.

    class EquipmentAndCosts {
      int cost1;
      int cost2;
      int canSelect;
      int timesChosen;
      String name;
    
      void timesChosenIncrease() {
        timesChosen++;
      }
    
      EquipmentAndCosts(
          {required this.name,
          required this.cost1,
          required this.cost2,
          required this.canSelect,
          required this.timesChosen});
    }