Dart Static Members
A static member belongs to the class itself. It exists once for the class, not once per object.
A static counter of instances
The constructor raises the shared counter each time it runs. The count is read through the class name.
class Student {
static int count = 0;
final String name;
Student(this.name) {
count++;
}
}
void main() {
Student('Ana');
Student('Ben');
Student('Cid');
print(Student.count);
}Static methods on a helper class
The converter class is never turned into an object. Its static methods are called through the class name.
class Converter {
static double toFahrenheit(double celsius) {
return celsius * 9 / 5 + 32;
}
static double toCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
}
void main() {
print(Converter.toFahrenheit(100));
print(Converter.toCelsius(212));
}A static const constant
The constants sit on the class itself. Reading them needs no object.
class Config {
static const String appName = 'Notes';
static const int maxItems = 50;
}
void main() {
print(Config.appName);
print(Config.maxItems);
}Example
class Account {
static int created = 0;
static const int maxAccounts = 3;
final String owner;
Account(this.owner) {
created++;
}
}
void main() {
final a = Account('Ana');
final b = Account('Ben');
print(a.owner);
print(b.owner);
print(Account.created);
print(Account.maxAccounts);
}Key points
- A static field is shared by every instance of the class.
- Code reaches a static member through the class name.
- Code reaches an instance member through an object.
- A static method can run without any instance at all.
- A static const holds a constant that belongs to the class.
- A static method cannot read instance fields directly.
In this example, owner is an instance field, so each account prints its own name through its object. The created counter and the maxAccounts constant belong to the class, so both are read through the Account name. Two constructor runs bring the counter to 2.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
How does code read a static field named total on a class named Report?