Dart Static

Summary: in this tutorial, you’ll learn how to use the Dart static keyword to define static fields and methods for a class.

Introduction to the Dart static keyword

A field is bound to a specific instance of a class. It means that each instance of the class has separate field values. So when you change the field value of one instance, it doesn’t affect other instances. Because of this, a field is often called an instance variable or instance field.

Unlike an instance field, a static field is bound to a class, not a specific instance of the class. It means that a static field is shared by all instances of the class.

To declare a static field, you use the static keyword like this:

static type staticField;Code language: Dart (dart)

To access a static field, you use the class name, dot notation, and field name as follows:

className.staticFieldCode language: Dart (dart)

For example:

class Point {
  int x;
  int y;
  static int _counter = 0;

  Point({this.x = 0, this.y = 0}) {
    _counter++;
  }
}

void main() {
  var p1 = new Point(x: 10, y: 20);
  var p2 = new Point(x: 100, y: 200);
  print(Point._counter); // 2
}Code language: Dart (dart)

Output:

2Code language: Dart (dart)

How it works.

First, define a Point class that has a static field called _counter:

static int _counter = 0;Code language: Dart (dart)

Second, increase the _counter by one in the constructor:

_counter++;Code language: Dart (dart)

Each time you create a new object, the value of the _counter is increased by one.

Third, create two new instances of the Point class:

var p1 = new Point(x: 10, y: 20);
var p2 = new Point(x: 100, y: 200);Code language: Dart (dart)

Finally, display the value of the _counter static field:

print(Point._counter); // 2Code language: Dart (dart)

As expected, the Point._counter returns 2 because we created two new instances of the Point class.

Dart static method

Since the static field _counter is private, you only can access it within the same library. To expose the _counter to other libraries, you can use the getter method.

Because the _counter is a static field, you can mark the getter as static like this:

class Point {
  int x;
  int y;
  Point({this.x = 0, this.y = 0}) {
    _counter++;
  }
  static int _counter = 0;
  static int get counter => _counter;
}

void main() {
  var p1 = new Point(x: 10, y: 20);
  var p2 = new Point(x: 100, y: 200);

  print(Point.counter); // 2
}Code language: Dart (dart)

Summary

  • Use the Dart static keyword to declare a static field or method in a class.
  • A static field or method is shared by all instances of the class. In other words, it is bound to the class.
Was this tutorial helpful ?