Search⌘ K
AI Features

Solution: Secure Bank Account

Explore how to create a secure bank account class in Dart by mastering private fields, constructors, getters, setters with validation, and overriding methods. Understand object encapsulation and data protection within Dart's OOP model to build maintainable and safe applications.

We'll cover the following...
Dart
class BankAccount {
String accountHolder;
double _balance;
BankAccount(this.accountHolder, this._balance);
BankAccount.newClient(this.accountHolder) : _balance = 0.0;
double get balance => _balance;
set balance(double newBalance) {
if (newBalance >= 0) {
_balance = newBalance;
} else {
print('Invalid balance update.');
}
}
@override
String toString() {
return 'Account: $accountHolder, Balance: \$$_balance';
}
}
void main() {
final acc = BankAccount.newClient('Alice');
acc.balance = 100.0;
acc.balance = -50.0;
print(acc);
}

Solution explanation

In the main.dart file:

  • Line 3: We declare _balance as a private backing field using the underscore prefix to prevent direct external ...