static
- Dart course
- Intermediate
- Lesson 22/116
- 5 min
Learn class-level members with static.
static
A static field belongs to the class itself, not to instances. All instances share the same value. It is written with the static keyword and accessed through the class name.
Example: class Counter { static int count = 0; Counter() { count++; } }. Here count is static; each new instance increments Counter.count. Access via instance c.count also works but is not recommended; the class name is the right form. Static fields fit counters, caches and configuration values.
static methods
Methods can also be static. A static method is called on the class name without an instance; it cannot reach instance fields, only static ones.
Example: class MathHelper { static int square(int n) => n * n; }. Here square is static; it is called as MathHelper.square(5), no instance needed. Writing MathHelper h = MathHelper(); h.square(5) is not wrong but is not recommended. Static methods fit helper functions and calculations; Dart's Math.sqrt and similar functions use this shape.
Practice Write Counter with static
Define a class named Counter. Add a static int count = 0; field. Write a Counter() { count++; } constructor. In main, create two instances with var a = Counter(); and var b = Counter();, then call print(Counter.count).
Starter code
// Define the Counter class
// Add a static count field and a constructor
void main() {
// Create two Counter instances and print Counter.count
}Sample solution
// Define the Counter class
class Counter {
static int count = 0;
Counter() {
count++;
}
}
void main() {
var a = Counter();
var b = Counter();
print(Counter.count);
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add the static keyword
class Counter {
____ int count = 0;
Counter() {
count++;
}
}
class Counter {
static int count = 0;
Counter() {
count++;
}
}
Explanation: A static field belongs to the class; all instances share it.
2 When two Counter instances are created, what is Counter.count?
- 0
- 2 Correct answer
- 1
- Throws an error
Explanation: Each constructor call increments count; two instances give 2.
3 Match the static parts
| Term | Meaning |
|---|---|
static |
Keyword |
Counter.count |
Access via class |
count++ |
Increment in constructor |