Sub topic 4
Static fields and methods
This chapter assumes you can write a basic Dart class with fields, methods, and a constructor, and that you understand final, const, and null safety. By the end you will know what static attaches to a class, when static fields are initialized, and when a top-level function is the better choice.
What static means
An instance member belongs to each object. Each Point has its own x and y. A static member belongs to the class itself. There is exactly one copy, and you reach it through the class name.
A static member has no this. Inside a static method you cannot read instance fields or call instance methods, because no particular object is involved.
Static fields
Declare a static field with the static keyword. The example below uses one to count how many objects exist.
class Counter {
static const int maxAllowed = 3;
static int _created = 0;
final int id;
Counter() : id = ++_created {
if (_created > maxAllowed) {
throw StateError('Too many counters');
}
}
static int get created => _created;
static void reset() => _created = 0;
}
void main() {
Counter();
Counter();
print(Counter.created);
print(Counter.maxAllowed);
Counter.reset();
print(Counter.created);
}This prints 2, 3, and 0. Three details in the example matter.
_createdis private to the library, not the class (see the previous chapter on privacy). Code in the same file can still read it.maxAllowedisstatic const, so it is a compile-time constant. Aconstfield in a class must be static.createdis a static getter. Getters and setters can be static in the same way as methods.
A non-nullable static field needs an initializer, or it must be marked late. You can write static late final String appName; and assign it once later. Reading it before assignment throws a LateInitializationError.
Static fields are lazy
Dart initializes a static field the first time something reads it, not when the program starts or when the class is first mentioned. The following example makes this visible with a print statement.
class Config {
static final Config instance = _load();
Config._();
static Config _load() {
print('loading');
return Config._();
}
}
void main() {
print('start');
final a = Config.instance;
final b = Config.instance;
print(identical(a, b));
}The output is start, then loading, then true. The initializer runs once, on the first read, and later reads reuse the stored value.
This laziness is why a static final field is a common way to build a simple singleton. It also explains a gotcha. If an initializer has side effects, such as reading a file or registering a listener, they happen at an unpredictable moment, not at startup. Keep static initializers cheap and free of side effects.
A static field initializer that refers to itself, directly or through another static field, causes a runtime error when it is first read.
Static methods
A static method is a function that lives in the class's namespace. Use it when the logic relates to the class but needs no instance. Typical uses are parsing helpers, validators, and unit conversions.
class Temperature {
final double celsius;
const Temperature(this.celsius);
static Temperature fromFahrenheit(double f) =>
Temperature((f - 32) * 5 / 9);
}
void main() {
final temps = [32.0, 212.0].map(Temperature.fromFahrenheit).toList();
print(temps.map((t) => t.celsius).toList());
}This prints [0.0, 100.0]. Static methods can be torn off, which means you pass Temperature.fromFahrenheit as a value without calling it. That is what map does above.
A static method that returns the class type looks a lot like a named constructor. The two differ in what they can do. A static method cannot appear in an initializer list or be a const constructor. It also cannot be the target of a redirecting constructor. If callers should write Temperature.fromFahrenheit(...) and you need none of those features, either form works. Prefer a named or factory constructor when the result is a new or cached instance of the class, because callers and tools then treat it as construction.
Rules and restrictions
You call a static member on the class, never on an instance.
class Animal {
static int count = 0;
static String kingdom() => 'Animalia';
String name;
Animal(this.name);
}
void main() {
print(Animal.kingdom());
final a = Animal('Rex');
// a.kingdom(); // error: instance access to a static member
// Animal.name; // error: name is an instance field
}Both commented lines fail to compile. Some other languages allow the first form, but Dart does not.
Static members are not inherited. If Dog extends Animal, then Dog.kingdom() is an error. You must write Animal.kingdom(), even inside the body of Dog. A subclass can declare its own static member with the same name. That is a separate member and does not override anything, because static members do not take part in dynamic dispatch.
Static members also cannot use the class's type parameters. In class Box<T>, a static method cannot mention T because there is no single T for the class as a whole. A static method can declare its own type parameter instead, as in static Box<R> of<R>(R value) => Box<R>(value);.
A mixin or extension can also declare static members. Those members are not mixed into the class that uses the mixin. You call them through the mixin's own name.
Static state and isolates
Each isolate has its own copy of every static field. Dart isolates do not share memory, so a static counter incremented in a background isolate leaves the main isolate's counter unchanged. In Flutter this matters when you use compute or Isolate.spawn. Anything the background isolate needs must be passed in as a message, not read from a static field.
Static versus top-level
Dart lets you declare functions and variables outside any class. The Dart style guide recommends avoiding classes that contain only static members, because a top-level function does the same job with less ceremony. The table compares the three options.
| Kind | Declared | Called as | Has `this` | Shares state |
|---|---|---|---|---|
| Instance method | inside a class | `object.method()` | yes | per object |
| Static method | inside a class with `static` | `ClassName.method()` | no | per class |
| Top-level function | outside any class | `method()` | no | per library |
Choose static when the member is closely tied to one class and its name reads naturally with the class prefix, such as Counter.reset(). Choose a top-level function when the helper is general and has no natural owner. You can also hide a top-level declaration from other libraries with a leading underscore.
Common errors
- Calling a static member on an instance. The fix is to use the class name.
- Reading an instance field in a static method. Pass the instance as a parameter, or make the method an instance method.
- Expecting subclasses to inherit statics. Qualify the call with the declaring class.
- Putting side effects in a static initializer. They run lazily, at the first read.
- Assuming statics are shared across isolates. They are not. Each isolate has its own copy.
Exercise
A class Session has static int _next = 1; and a final field id. You want each new Session to receive the next number (1, 2, 3, ...) with no help from the caller. Write the constructor, and explain why _next cannot be an instance field.
Show answer
Use an initializer list that reads and increments the static field: Session() : id = _next++;. The initializer runs before the constructor body, so id is set once, as a final field requires. _next must be static because an instance field would give every Session its own copy starting at 1, so every id would be 1. A static field has one copy shared by all instances, which lets the counter carry across constructions.
Exercise
Given class Animal { static String kingdom() => 'Animalia'; } and class Dog extends Animal {}, does Dog.kingdom() compile? What is the correct call, and what happens if Dog declares its own static String kingdom() => 'Dog kingdom';?
Show answer
Dog.kingdom() does not compile, because static members are not inherited. The correct call is Animal.kingdom(). If Dog declares its own static kingdom, Dog.kingdom() calls that new method and Animal.kingdom() still returns 'Animalia'. The two are unrelated members, and the one in Dog does not override the one in Animal.