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?