skip to Main Content

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,

2

Answers


  1. Chosen as BEST ANSWER

    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});
    }


  2. The problem here is that you are trying to update the timesChosen property of an instance of ListItem using the timesChosen++ expression, which assumes the presence of a setter for that property. For you code to work, you should ensure that the ListItem class has a setter method for the timesChosen property. Below is an example with the setter:

    class ListItem {
      int cost1;
      int cost2;
      int canSelect;
      int _timesChosen; // hold the value of timesChosen
    
      String name;
    
      // Getter for timesChosen
      int get timesChosen => _timesChosen;
    
      // Setter for timesChosen
      set timesChosen(int value) {
        _timesChosen = value;
      }
    
      ListItem(this._timesChosen, {required this.cost1, required this.cost2, required this.canSelect, required this.name});
    }
    

    The above code snippet should work with the code in your listview.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search