Dart: How are varibles in nested functions bound to parent's local variables?

229

#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.

Share:
229
Alexey Inkin
Author by

Alexey Inkin

I am a programmer and a photographer. I develop my Learning Management System and a CMS for online shops.

Updated on December 26, 2022

Comments

  • Alexey Inkin
    Alexey Inkin over 1 year

    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:

    1. What are the exact mechanics of such bindings? What exactly creates a new scope? Is it documented?
    2. Does 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 vars on each iteration?