Chapter 5 - closures and scope example doesn't work

In the “Closures and Scope” section, just before the exercises, there is an example that doesn’t work for me.

Function countingFunction() {
  var counter = 0;
  final incrementCounter = () {
    counter += 1;
    return counter;
  };
  return incrementCounter;
}

When I run:

final counter1 = countingFunction();
final counter2 = countingFunction();
print(counter1()); // 1
print(counter2()); // 1
print(counter1()); // 2
print(counter1()); // 3
print(counter2()); // 2

I get the following notification:

2 Closure: () => int

Any ideas? I tried a few things but couldn’t get it sorted.

If I paste the following into dartpad.dev it works for me:

void main() {
  final counter1 = countingFunction();
  final counter2 = countingFunction();
  print(counter1()); // 1
  print(counter2()); // 1
  print(counter1()); // 2
  print(counter1()); // 3
  print(counter2()); // 2
}

Function countingFunction() {
  var counter = 0;
  final incrementCounter = () {
    counter += 1;
    return counter;
  };
  return incrementCounter;
}

I’m not sure why it isn’t working for you. Is your main function the same? Are you using the newest version of Dart?

Hey Suragch, thanks for taking a look. I’m not sure where I messed up but it looks like my print function was missing the () after counter1/2. It all works now, sorry about the mix up, I must have been staring at the screen too long.

1 Like