supplying values for parameters to function calls within an onPressed callback in flutter

Viewed 16

I have an app with a list of buttons on the same screen. The onPressed functions for all the buttons include a call to a particular function, but each with different parameter values, which are determined at run time. My first attempt at this was along the lines of

  _MyHomePageState() {
List<int> vals = [1,2];  //in real application these values are computed by earlier code
int v;
for(int i=0; i<vals.length; i++) {
  v=vals[i];
  butns.add(ElevatedButton(
            onPressed:(){ doSomething(v);}, 
            child: Text('$v')));    
}

But this does not work - all the buttons use the parameter values supplied for the last button (in this case, 2)

changing the parameter in doSomething() to refer to the list of values, rather than the variable v does work

 _MyHomePageState() {
List<int> vals = [1,2];  //in real application these values are computed by earlier code
int v;
for(int i=0; i<vals.length; i++) {
  v=vals[i];
  butns.add(ElevatedButton(
          onPressed:(){ doSomething(vals[i]);}, 
          child: Text('$v')));    
}

Can someone explain why v can be used for the Text widget for the buttons' labels but not in the onPressed() function?

1 Answers

You declare v outside of the for. on pressed gets called after v has been assigned to 2 and this does not save the state of v, it saves only the reference to v; If you change v over time, the doSomething method gets the currently set value of v.

Related