Member-only story
Encapsulation in Dart
Encapsulation is a fundamental principle of object-oriented programming that restricts direct access to an object’s internal data and only exposes what is necessary. In Dart, encapsulation is achieved using private fields (prefixed with _) and controlled access through getters and setters.
Read Medium Story for free 👇
Why Use Encapsulation?
- Data Protection: Prevents unwanted modification of properties.
- Controlled Access: Only allows specific ways to read or update data.
- Improved Maintainability: Makes code easier to manage and update.
Example of Encapsulation
class BankAccount {
String _accountNumber;
double _balance;
BankAccount(this._accountNumber, this._balance);
// Getter for balance (read-only)
double get balance => _balance;
// Setter for deposit (write-only)
void deposit(double amount) {
if (amount > 0) {
_balance += amount;
} else {
print('Deposit amount must be positive.');
}
}
// Setter for withdrawal with…









