private
- Dart course
- Intermediate
- Lesson 18/116
- 5 min
Learn private members with _.
private fields
In Dart a field is made private by prefixing its name with an underscore: _balance. This gives library level privacy; the field is reachable inside the same library (file) but not from other libraries.
Example: class Account { double _balance; Account(this._balance); }. Here _balance is private; from outside the file of the Account class, a._balance cannot be reached. Dart has no private keyword; privacy starts with the underscore prefix. This approach blocks direct mutation from outside; access happens through methods.
Library level privacy
Dart privacy is tied to the library concept. A library is usually a single file; so underscored fields are reachable from the same file but not from other files.
Example: if _balance is defined in account.dart, writing a._balance in main.dart gives a compile error. A method in the same account.dart can reach the field freely. So Dart privacy works at the file boundary, not the class boundary. Combining many files into one library is possible with the part directive; then all files share the same library.
Practice Add a private field to Account
Define a class named Account. Add a private String _owner field. Write an Account(this._owner) constructor. Add a void show() { print(_owner); } method. In main, create an instance with var a = Account('Alex'); and call a.show().
Starter code
// Define the Account class
// Add a private _owner field, a constructor and a show method
void main() {
// Create an Account('Alex') instance and call show()
}Sample solution
// Define the Account class
class Account {
String _owner;
Account(this._owner);
void show() {
print(_owner);
}
}
void main() {
var a = Account('Alex');
a.show();
}Expected output
Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a private field in Dart?
- private balance
- _balance Correct answer
- balance#
- balance.private
Explanation: The underscore prefix is Dart's private marker.
2 Name the private field
class Account {
double ____;
Account(this._balance);
}
class Account {
double _balance;
Account(this._balance);
}
Explanation: The underscore prefix makes the field private.
3 Match the private parts
| Term | Meaning |
|---|---|
_ |
Private prefix |
_balance |
Private field |
Account |
Class name |