Class variables and methods
Use the static
keyword to implement class-wide variables and methods.
Static variables
Static variables (class variables) are useful for class-wide state andconstants:
class Queue {
static const initialCapacity = 16;
// ···
}
void main() {
assert(Queue.initialCapacity == 16);
}
Static variables aren’t initialized until they’re used.
Note: This page follows the style guide recommendation of preferring lowerCamelCase
for constant names.
Static methods
Static methods (class methods) do not operate on an instance, and thusdo not have access to this
. For example:
import 'dart:math';
class Point {
num x, y;
Point(this.x, this.y);
static num distanceBetween(Point a, Point b) {
var dx = a.x - b.x;
var dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
}
void main() {
var a = Point(2, 2);
var b = Point(4, 4);
var distance = Point.distanceBetween(a, b);
assert(2.8 < distance && distance < 2.9);
print(distance);
}
Note: Consider using top-level functions, instead of static methods, for common or widely used utilities and functionality.
You can use static methods as compile-time constants. For example, youcan pass a static method as a parameter to a constant constructor.