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:

  1. class Queue {
  2. static const initialCapacity = 16;
  3. // ···
  4. }
  5. void main() {
  6. assert(Queue.initialCapacity == 16);
  7. }

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:

  1. import 'dart:math';
  2. class Point {
  3. num x, y;
  4. Point(this.x, this.y);
  5. static num distanceBetween(Point a, Point b) {
  6. var dx = a.x - b.x;
  7. var dy = a.y - b.y;
  8. return sqrt(dx * dx + dy * dy);
  9. }
  10. }
  11. void main() {
  12. var a = Point(2, 2);
  13. var b = Point(4, 4);
  14. var distance = Point.distanceBetween(a, b);
  15. assert(2.8 < distance && distance < 2.9);
  16. print(distance);
  17. }

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.