Sitemap
Dart Tutorials

Dart Tutorials for beginners and advanced programmers

Encapsulation in Dart

3 min readMar 27, 2025

--

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.

Press enter or click to view image in full size

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…

--

--

Usama Sarwar
Usama Sarwar

Written by Usama Sarwar

Helping founders turn ideas into market-ready web and mobile apps within 30 days using Google’s Flutter & Next.js without juggling multiple teams.

Dart Tutorials
Dart Tutorials

Published in Dart Tutorials

Dart Tutorials for beginners and advanced programmers