A Dart visibilty primer for Java devs
If you are new to Dart and Flutter, you may have wondered why some identifiers start with an underscore. As you will see shortly, this is related to visibility and scope. The underlying questions are
- Where can I see a variable, function or method?
- Where and when can I access them?
To start with, consider the following source file named a.dart. Yes, no underscore… :-)
var answer = 42;
var a = answer;
var b = a;
It will not work. If you try to run it, you get Error: Getter not found: ‘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 Getter not found? 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 dart file (to be more precisely: library) that imports a_correct.dart. But what if we don’t want a variable or function to 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.
A previous version of this article was published 2017/02/06 on my Blogger.com blog Tommis Blog. I deleted the weblog in the wake of the GDPR (General Data Protection Regulation), so the original post is no longer available (or only through the Wayback machine of the Internet Archive).
If not stated otherwise images are © Thomas Künneth