I have some Dart/Flutter code the essentially does this:

for(int i = 0; i < dataArray.length; i++){
     int curr = i;
     table.add(
          new DataRow(
               ...
               onSelectChanged: (bool selected){
                    DataRow toSwap = table[curr]; 
                    /*This is how I "get" a row to select it, 
                    as there is no getter for the "checked" property*/
                    ...
               }
          )
     );
}

I need to use the curr variable in this callback, but, by the time it is called in the method, it reflects the iterator's final value. How can I use the value of curr at the time of adding the callback in Dart?


Solution 1: Herbert Poul

I assume you modified your code before posting it.. as jamesdlin comment shows, your code would work. So to solve your original problem, you simply have to create a new variable for each iteration, I assume your original code had the variable defined outside the loop.

ie, to show by @jamesdlin example:

  // working as expected
  for (int i = 0; i < 10; i += 1) {
    final int current = i;
    functionList.add(() => print('$i $current')); // 0 0, 1 1, 2 2, ...
  }

  // current will be updated
  int current;
  for (int i = 0; i < 10; i += 1) {
    current = i;
    functionList.add(() => print('$i $current')); // 0 9, 1 9, 2 9, ...
  }

in summary: mutable state is evil ;-) embrace final, so you are not tempted to create your variables outside of the loop anyway.