Sub topic 3
Privacy with a leading underscore
This chapter assumes you can write a basic Dart class with fields and methods, and that you know how import works. It covers how Dart hides members, why the unit of privacy is the library and not the class, and the patterns that follow from that.
Dart has no `private` keyword
Many languages mark members with private, protected, and public. Dart has none of these. A name that starts with an underscore (_) is private. Any other name is public.
class Account {
Account(this.owner, double opening) : _balance = opening;
final String owner; // public
double _balance; // private
double get balance => _balance; // public read-only view
void deposit(double amount) {
if (amount <= 0) {
throw ArgumentError.value(amount, 'amount', 'must be positive');
}
_balance += amount;
}
bool _isOverdrawn() => _balance < 0; // private method
}The underscore works on fields, methods, getters, setters, constructors, top-level functions, top-level variables, classes, enums, and typedefs. The rule is the same for all of them.
The boundary is the library
Dart enforces privacy per library, not per class. By default, one .dart file is one library. A private name can be used anywhere in the same library and nowhere else.
Save the class above as account.dart. Then create main.dart in the same folder:
import 'account.dart';
void main() {
final account = Account('Ana', 100);
account.deposit(50);
print(account.balance); // 150.0
// account._balance = 0;
// Error: The setter '_balance' isn't defined for the class 'Account'.
}The compiler rejects the commented-out line, so the error appears at compile time, before the program runs.
Other classes in the same file can see the member
Because the boundary is the library, a second class in account.dart can read _balance. A top-level function in that file can too:
class Account {
Account(this.owner, double opening) : _balance = opening;
final String owner;
double _balance;
double get balance => _balance;
}
class Auditor {
// Legal: Auditor and Account are in the same library.
bool isOverdrawn(Account account) => account._balance < 0;
}
void main() {
final auditor = Auditor();
print(auditor.isOverdrawn(Account('Ana', -5))); // true
}If you come from Java or C#, this is the main surprise. Dart's privacy hides members from other libraries, not from other classes. Dart also has no protected. A subclass in another library gets no access to private members of its superclass.
Multi-file libraries
A part file belongs to the same library as the file that declares it. Private names are shared across all parts.
// shapes.dart
library;
part 'shapes_helpers.dart';
class Shape {
final double _scale = 2;
}// shapes_helpers.dart
part of 'shapes.dart';
double scaled(Shape shape, double value) => value * shape._scale;Use part sparingly. It is mostly useful for generated code, such as the files produced by build_runner, which need access to private members.
Common patterns
Private field with a public getter
This is the usual way to expose state as read-only. Callers can read balance but cannot assign to it. Only code in the library can change _balance. The Account class above uses this pattern.
A getter and its matching setter share a name, so they share privacy. You cannot declare double get _balance together with set balance(...) and have them pair up. They are two unrelated members.
Private constructors
A constructor whose name starts with an underscore is private. Two patterns depend on it.
The first is the cached factory from the spine, where only the factory can call the real constructor:
class Logger {
final String name;
static final Map<String, Logger> _cache = {};
factory Logger(String name) {
return _cache.putIfAbsent(name, () => Logger._internal(name));
}
Logger._internal(this.name);
void log(String message) => print('[$name] $message');
}Code outside the library cannot call Logger._internal. The only way to get a Logger is the factory, so the cache cannot be bypassed.
The second is a class that should never be instantiated, such as a group of constants and helpers:
class Palette {
Palette._(); // no one outside this library can create a Palette
static const int primary = 0xFF2196F3;
static const int accent = 0xFFFF9800;
}Without any constructor, Dart adds a public default one. Declaring Palette._() suppresses it.
Private classes and top-level declarations
Prefix a class with an underscore to keep it as an implementation detail:
class _Entry {
_Entry(this.key, this.value);
final String key;
final Object? value;
}
class Registry {
final List<_Entry> _entries = [];
void put(String key, Object? value) => _entries.add(_Entry(key, value));
Object? get(String key) {
for (final entry in _entries) {
if (entry.key == key) return entry.value;
}
return null;
}
}Avoid putting a private type in a public signature, as in List<_Entry> get entries. Outside callers receive values of a type they cannot name. They cannot write _Entry in their own declarations, and they cannot call _Entry(...). The library_private_types_in_public_api lint warns about this.
Gotchas
Subclasses in other libraries cannot override private members. A name _helper in library A and a name _helper in library B are different names. The compiler treats the underscore name as scoped to its library. If a subclass in library B declares _helper, it does not override the superclass method. It declares an unrelated member.
// base.dart
class Base {
String run() => _step();
String _step() => 'base';
}// main.dart
import 'base.dart';
class Child extends Base {
String _step() => 'child'; // a new, unrelated method
}
void main() {
print(Child().run()); // base
}Here run calls Base._step, and Child._step is not involved. The @override annotation on Child._step would be an error.
Private does not mean secret. Privacy is a compile-time check. It is a design tool for protecting your invariants. It does not hide data from a debugger, from toString output you write yourself, or from tools that read memory. Do not store secrets in a private field and call that security.
Named parameters have a restriction. A named parameter cannot start with an underscore, because callers in other libraries could not write the name. Positional parameters can start with an underscore, as in Account(this._balance). For a private field fed from a named parameter, use an initializer list:
class Counter {
Counter({int start = 0}) : _count = start;
int _count;
int get count => _count;
void increment() => _count++;
}Choosing what to make private
| Member | Make it private when |
|---|---|
| Mutable field | Changes must go through methods that keep the object valid. |
| Helper method | It only makes sense as a step inside another method. |
| Constructor | Creation must go through a factory, or the class is a namespace. |
| Class | It is an implementation detail of a public class in the same library. |
| `final` field | Usually keep it public. A public `final` field cannot be reassigned, so exposing it is safe. |
A common mistake is to write a private field and a getter that return the same thing, plus a setter that assigns it without checks. That is a public field with extra steps. Add a getter or setter only when it adds validation, computes a value, or restricts access.
Exercises
Exercise
You declare class Wallet { int _cents = 0; } in wallet.dart and class Shop { void refund(Wallet w) { w._cents += 100; } } in the same file. Does this compile? What changes if Shop moves to shop.dart and imports wallet.dart?
Show answer
It compiles in the same file, because privacy is per library and both classes are in the library wallet.dart. After the move, Shop is in a different library, so w._cents is a compile-time error. To allow the refund, expose a public method such as void credit(int cents) on Wallet.
Exercise
A library declares class Base { String run() => _step(); String _step() => 'base'; }. In another library, class Child extends Base { String _step() => 'child'; }. What does Child().run() return, and why?
Show answer
It returns 'base'. The name _step is scoped to the library that declares it, so Child._step in the second library is a different member from Base._step and does not override it. run is defined in Base, so it calls Base._step.