Sub topic 4
Static Fields and Methods in Dart
This chapter assumes you know basic Dart syntax, null safety, classes, and instance methods. You will learn how to store data and behavior that belong to a class itself rather than to one particular object.
Class-level members
A static member belongs to the class. Dart creates one shared static field for the class, not one copy for every object. A static method can be called without creating an object.
Use the class name to access static members:
class Temperature {
static const double freezingCelsius = 0;
static int conversions = 0;
final double celsius;
Temperature(this.celsius);
double toFahrenheit() {
return celsius * 9 / 5 + 32;
}
static double celsiusFromFahrenheit(double fahrenheit) {
conversions++;
return (fahrenheit - 32) * 5 / 9;
}
}
void main() {
final room = Temperature(21);
print(room.toFahrenheit());
print(Temperature.freezingCelsius);
final outdoor = Temperature.celsiusFromFahrenheit(86);
print(outdoor);
print(Temperature.conversions);
}celsius belongs to each Temperature object. The freezingCelsius constant and conversions counter belong to the Temperature class.
The call to room.toFahrenheit() needs an object because the method uses that object's celsius field. The call to Temperature.celsiusFromFahrenheit(86) does not need an object because the method only uses its parameter and the static conversions field.
| Member kind | Belongs to | Access example |
|---|---|---|
| Instance field | One object | `room.celsius` |
| Instance method | One object | `room.toFahrenheit()` |
| Static field | The class | `Temperature.conversions` |
| Static method | The class | `Temperature.celsiusFromFahrenheit(86)` |
Rules and common errors
A static method cannot directly read or call an instance member. There is no particular object for it to use.
class User {
final String name;
User(this.name);
static void printName() {
// print(name); // Error: no User object is available here.
}
}Pass the required value as an argument, or call the method on an object instead:
class User {
final String name;
User(this.name);
static void printProvidedName(String name) {
print(name);
}
void printOwnName() {
print(name);
}
}Static state is useful for constants, counters, registries, caches, and utility operations. However, mutable static fields are global shared state. Any part of the program can change them, which can make tests and debugging harder.
How static access works
A static member can also be private by starting its name with an underscore. Privacy is scoped to the Dart library, so a private static cache can hide implementation details from other libraries.
Exercise
In class Counter { static int total = 0; final int value; Counter(this.value); }, which expression accesses the shared counter: Counter.total or Counter(3).total?
Show answer
Counter.total is correct because total is static and belongs to the class, not to an individual object.