Public and Private Members
Public and Private Members
About
- Public Members: Visible to all code (default)
- Private Members: Visible only within library (
_
prefix) - Applies to class fields, methods, top-level variables
- Essential for encapsulation
Main Topics
-
Public Access
- Definition: Default visibility
- Example:
class User { String name; // Public by default }
-
Private Members
- Definition:
_
prefix convention - Example:
class User { String _id; // Private to library }
- Definition:
-
Method Visibility
-
Definition: Applying to methods
-
Example:
class Calculator { int _current = 0; void _reset() { // Private method _current = 0; } }
-
-
Top-level Privacy
- Definition: Outside classes
- Example:
String publicVar = 'visible'; String _privateVar = 'hidden';
-
Getter/Setter Control
-
Definition: Exposing private fields
-
Example:
class Wallet { double _balance = 0; double get balance => _balance; // Public read-only }
-
How to Use
- Encapsulation: Hide implementation details
- API Design: Expose only what’s needed
- Naming:
_
prefix for private members - Testing: Use library structure for access
How It Works
- Compilation:
_
prefix triggers privacy - Scope: Library boundary enforcement
- Visibility: Analyzer enforces access rules
- Tooling: IDE shows visibility cues
Example:
class BankAccount {
String _accountNumber; // Private
double balance = 0; // Public
BankAccount(this._accountNumber);
void _logTransaction() { // Private
print('Transaction for $_accountNumber');
}
}
Conclusion
Dart’s public/private access control through naming conventions provides a simple yet effective way to manage encapsulation. By prefixing members with _, developers can hide implementation details while exposing clean public APIs, leading to more maintainable code.