// ref – https://stackoverflow.com/questions/17488611/how-to-create-private-variables-in-dart/17488825
There is no private, public, protected in Dart. However we use _ to hide data at the library level, and then use getter and setters to expose these data.
In our example, we declare _balance to be a library level private variable.
We expose this to the world through getter balance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class BankAccount { BankAccount(this._balance); double _balance; // library level privacy String get balance => 'Your balance is: $_balance'; void deposit(double amount) { _balance += amount; } void withdraw(double amount) { if (_balance > amount) { _balance -= amount; } } } |
1 2 3 4 5 6 7 8 |
import 'BankAccount.dart'; void main() { final ba = BankAccount(100); print(ba.balance); ba.deposit(243); print(ba.balance); } |