Dart - How do I pass an iterator value into a callback in Dart?
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.
Isaac Krementsov
I am an enthusiastic web and mobile developer with a versatile skill set. At the beginning of my programming experience, I recognized that I was never done learning. Since then, I have become most familiar with using ExpressJS, MongoDB, Go, Java, HTML5, and more while continuously adding to that list. Whether you simply want to make your website known or need a real-time application, I am here to help.
Updated on December 10, 2022Comments
-
Isaac Krementsov over 1 year
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 ofcurr
at the time of adding the callback in Dart?-
jamesdlin about 5 yearsI can't reproduce your problem. Can you please post a minimal, complete, verifiable example?
-