- Where can I see a variable, function or method?
- Where and when can I access them?
var answer = 42;
var a = answer;
var b = a;
It will print 42 once, but then fail with a NoSuchMethodError. That happens because there is no top-level getter b. To a Java developer it will not be surprising that print(b); outside the nested block fails, as b is not visible here. But why do we see NoSuchMethodError? Didn't I just access an identifier?
In Dart access to variables occurs via getters and setters, and if these have not been defined by the developer, they will be there automatically. If we remove the second print(), the program will run just fine (assume a version named a_correct.dart). Now take a look at the following lines of code:
If we run it, 42 is printed once. In a_correct.dart answer has been declared at the top-level, so the identifier can be seen by the library that imports a_correct.dart. But what if we don't want a variable or function be visible? Just prefix the identifier with an underscore. Imagine a file b.dart:
var _answer = 42;
Not to much surprise, it will fail. Neither _hello() nor _answer are visible. There is more control about what packages export to the outside world, but this is an advanced topic I might cover later. So, for now dear Java devs, just forget about public, private and protected. And stick to this simple rule:
If it's local, prefix the identifier with an underscore.