A leading underscore character (
_ ) indicates that a member is private to its library. This is not mere convention, but is built into the language itself.
PREFER making declarations private.
A public declaration in a library — either top level or in a class — is a signal that other libraries can and should access that member. It is also a commitment on your library’s part to support that and behave properly when it happens.
If that’s not what you intend, add the little
_ and be happy. Narrow public interfaces are easier for you to maintain and easier for users to learn. As a nice bonus, the analyzer will tell you about unused private declarations so you can delete dead code. It can’t do that if the member is public because it doesn’t know if any code outside of its view is using it.
CONSIDER declaring multiple classes in the same library.
Some languages, such as Java, tie the organization of files to the organization of classes — each file may only define a single top level class. Dart does not have that limitation. Libraries are distinct entities separate from classes. It’s perfectly fine for a single library to contain multiple classes, top level variables, and functions if they all logically belong together.
Placing multiple classes together in one library can enable some useful patterns. Since privacy in Dart works at the library level, not the class level, this is a way to define “friend” classes like you might in C++. Every class declared in the same library can access each other’s private members, but code outside of that library cannot.
Of course, this guideline doesn’t mean you should put all of your classes into a huge monolithic library, just that you are allowed to place more than one class in a single library.