In Dart, privacy is at the library (file) level. Static members belong to the class itself rather than any specific object instance.
1. Private Members (_)
Dart does not have private or public keywords. Instead, you add an underscore _ to the start of a name to make it private to its file.
Encapsulation
1class BankAccount {2 double _balance = 0; // Private3 4 void deposit(double amount) {5 _balance += amount;6 }7 8 // Public getter to read the value9 double get balance => _balance;10}11 12// In main.dart (different file):13// var account = BankAccount();14// account._balance = 1000; // ❌ Error: Cannot access private field15// print(account.balance); // ✅ OK: Using getterHintPrivacy prevents other code from messing with internal state directly. They must use your methods/getters.
2. Getters and Setters
You can control how fields are accessed or modified using get and set keywords.
Controlled Access
1class Temperature {2 double _celsius = 0;3 4 // Getter5 double get celsius => _celsius;6 7 // Setter with validation8 set celsius(double value) {9 if (value < -273.15) {10 print('Invalid temperature!');11 } else {12 _celsius = value;13 }14 }15 16 // Computed Property17 double get fahrenheit => (_celsius * 9 / 5) + 32;18}HintComputed properties like fahrenheit act like fields but calculate their value dynamically.
3. Static Members
A static variable or method belongs to the Class, not the Object. It is shared across all instances.
Shared Data
1class Constants {2 static const double pi = 3.14159;3 static int userCount = 0;4 5 Constants() {6 userCount++; // Increment every time a generic object is created? 7 // Usually static is used for utilities, not instance tracking this way.8 }9 10 static double calculateCircleArea(double radius) {11 return pi * radius * radius;12 }13}14 15void main() {16 print(Constants.pi); // Access via Class Name17 print(Constants.calculateCircleArea(10));18 19 // Constants c = Constants();20 // print(c.pi); // ❌ Error: Static member cannot be accessed via instance21}HintUse static for utility functions (like Math.max) or global configuration constants.
Loot collected
Key takeaways- Prepend
_to a variable or method name to make it private to the file. - Use getters/setters to validate data or define computed properties.
- use
staticfor constants and utility methods that do not rely on instance data. - You access static members using the Class name (e.g.,
Color.red), not an object variable.
Side quests
Practice exercises
Exercise 1: Private Field
Create a class Secret with a private string _code. Add a method checkCode(String input) to verify it.
Reveal solutionHide solution
1class Secret { String _code = '123'; bool checkCode(String input) => input == _code; }Exercise 2: Static Math
Create a class MathUtils with a static method add(a, b) that returns the sum.
Reveal solutionHide solution
1class MathUtils { static int add(int a, int b) => a + b; }