Reputation: 2049
I create elements in a loop and need different callback values for each. This code does it:
for (var obj in objects) {
result.add(
content: GestureDetector(
child: Text(obj.title),
onTap: () => widget.onTap(obj), // Correct object is bound on each loop iteration.
),
);
}
However this works differently:
var obj;
for (var i = 0; i < objects.length; i++) {
obj = objects[i];
result.add(
content: GestureDetector(
child: Text(obj.title),
onTap: () => widget.onTap(obj), // Always get the last object in array.
),
);
}
The latter is actually expected and the former makes me wonder why it worked in the first place. Looks like var
creates a new variable in each iteration, and it is preserved in the binding. My questions are:
var
in a loop impact performance and memory? If I do not need bindings, is var i; for (i = ...
better than for (var i = ...
because it does not create var
s on each iteration?Upvotes: 1
Views: 437
Reputation: 44131
#1 ... The bindings are often referenced as "closure bindings", because variables that are out of the scope of the closure, but still in scope for the code in the closure, are in fact part of the bindings.
As for your #2 question, if nobody captures the value in a closure, the same variable is used for all iterations, so you don't need to microoptimize the speed.
Upvotes: 2