Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 61 ยท Classes and Object-Oriented Dart

Static Members, Constants and Callable Classes

Learn Dart static fields and methods, static constants, const constructors and canonical instances, the singleton pattern with factories, and callable classes.

So far, every field and method you wrote belonged to an object: each Point has its own x and y. Sometimes a piece of data or behavior belongs to the class itself: a counter shared by all instances, a constant such as the maximum size, a helper that does not need any object state. Dart calls these static members.

This lesson also covers three related ideas: constants and const constructors, which let Dart share identical objects; the singleton pattern, which uses a factory constructor to hand out one shared instance; and callable classes, whose objects can be invoked like functions. The Dart code is read-only, and TypeScript stand-ins run the same ideas.

Static fields and methods

Put static in front of a field or method and it is attached to the class. You access it through the class name, never through an instance:

DART
class Counter {
  static int created = 0;

  Counter() {
    created++;
  }

  static String describe() => '$created counter(s) created';
}

void main() {
  Counter();
  Counter();
  print(Counter.created);      // 2
  print(Counter.describe());   // 2 counter(s) created
}

Static members have no this. A static method cannot read instance fields, because it does not run on any object. Static fields are initialized lazily, the first time they are read, so an expensive static initializer costs nothing until you need it.

Use statics when the data truly belongs to the type: a registry, a cache, a counter, or a factory helper such as Color.fromHex('#ff0000'). Do not use them as global variables in disguise. Mutable statics make code hard to test, because state leaks between tests. Prefer passing dependencies in through constructors, and keep statics for constants and pure helpers.

Static members are not inherited by instances and are not part of an interface. A subclass can still reach Parent.helper() by using the parent's name. There are no static overrides.

Static constants

A constant that belongs to the class is static const:

DART
class Limits {
  static const int maxUsers = 100;
  static const double taxRate = 0.2;
  static const List<String> roles = ['admin', 'editor', 'viewer'];
}

void main() {
  print(Limits.maxUsers);     // 100
  print(Limits.roles.length); // 3
}

A static const value is a compile-time constant, so it can be used in other constant expressions, default parameter values and annotations. A static final value, in contrast, is computed once at runtime on first use, for example static final DateTime started = DateTime.now();. Reach for const whenever the value is known at compile time. The difference between final and const is explained in Variables, var, final and const.

Note that const makes a collection deeply immutable: Limits.roles.add('guest') throws an UnsupportedError.

TypeScript Class-level state and constants (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

const constructors and canonical instances

If every field of a class is final, you can give it a const constructor. Calling that constructor in a constant context creates a compile-time constant object, and Dart canonicalizes it: two constant expressions with the same arguments produce the very same object in memory.

DART
class Point {
  const Point(this.x, this.y);
  final int x;
  final int y;
}

void main() {
  const a = Point(1, 2);
  const b = Point(1, 2);
  final c = Point(1, 2);          // not constant: new object at runtime

  print(identical(a, b));         // true: one shared object
  print(identical(a, c));         // false
}

Canonicalization saves memory and makes identical checks cheap. It is also why Flutter code is full of const widgets: an unchanged constant subtree is skipped when the screen rebuilds. A const constructor has restrictions: no body, only initializer lists with constant expressions, and all instance fields final. If any field is a mutable object, the constant is only shallowly immutable.

flowchart LR
    A["const Point(1, 2)<br/>in file A"] --> O["One shared Point<br/>x=1, y=2"]
    B["const Point(1, 2)<br/>in file B"] --> O
    C["Point(1, 2)<br/>at runtime"] --> N["A new Point<br/>x=1, y=2"]

Equal constant expressions share one canonical object; a non-constant call always allocates a new one.

The singleton pattern

Sometimes you want exactly one instance, such as a configuration object or a logger. In Dart, the idiom combines a private constructor, a static field and a factory constructor:

DART
class Settings {
  Settings._internal();                         // private named constructor
  static final Settings _instance = Settings._internal();

  factory Settings() => _instance;              // always returns the same object

  String theme = 'light';
}

void main() {
  final a = Settings();
  final b = Settings();
  a.theme = 'dark';
  print(b.theme);               // dark
  print(identical(a, b));       // true
}

The _internal name begins with an underscore, so only code in the same library can call it. The static field initializes lazily on first use, so the object is created only when something asks for it. Each isolate has its own copy of statics, so the instance is unique per isolate, not per process. A factory constructor may return an existing object, which an ordinary generative constructor cannot, so the call site still reads Settings(). Factory constructors are covered in Constructors.

Use singletons sparingly. They behave like globals, and tests find them hard to replace. A better approach is often to create the object once near main and pass it down.

TypeScript A singleton with a private constructor (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Callable classes

If a class defines a method named call, its instances can be invoked with parentheses as if they were functions:

DART
class Multiplier {
  const Multiplier(this.factor);
  final int factor;

  int call(int value) => value * factor;
}

void main() {
  const triple = Multiplier(3);
  print(triple(5));                       // 15, same as triple.call(5)
  print([1, 2, 3].map(triple).toList());  // [3, 6, 9]
}

An instance of Multiplier can be passed anywhere a function type such as int Function(int) is expected, because the compiler treats call as the function's body and the object as its holder of state. This is useful when a function needs configuration or memory between calls, such as a rate limiter or a cache wrapper. Where a closure would do, use a closure (see First-Class Functions, Closures and Typedefs). Where you also want named fields, extra methods or a const instance, a callable class is neater.

TypeScript A callable object that carries state (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you access a static field created of class Counter?

    Static members belong to the class, so you reach them through the class name, not through an instance.
  2. 2. What is true about const Point(1, 2) == const Point(1, 2) when Point has a const constructor and no custom ==?

    Equal constant expressions are canonicalized, so both refer to one object and even the default identity-based == returns true.
  3. 3. Which requirement applies to a class with a const constructor?

    A const constructor needs all instance fields to be final (and a constant-only initializer list), so the object cannot change.
  4. 4. What lets triple(5) work when triple is an instance of a class?

    Defining a method called call makes instances callable, so triple(5) means triple.call(5).
  5. 5. Why does the singleton idiom use a factory constructor?

    Unlike a generative constructor, a factory may return any compatible object, including a cached one, so Settings() always yields the same instance.

Summary

  • static members belong to the class and are accessed through its name; they have no this and are initialized lazily.
  • static const defines compile-time constants; prefer const over final when the value is known at compile time.
  • A const constructor (all fields final) creates canonical objects: equal constant expressions share one instance.
  • The singleton idiom is a private named constructor, a static final instance and a factory constructor, but use it sparingly.
  • A method named call makes instances callable like functions.

Next, handle things going wrong in Exceptions and Error Handling.