Skip to main content
A static field is a variable declared within a class definition using the static modifier. Unlike instance fields, which are allocated per object instantiation, a static field belongs to the class itself. It occupies a single storage location in memory that is shared across all instances of that class within the running isolate.

Declaration Syntax

Static fields are defined by prefixing the variable declaration with the static keyword. They may be mutable, final, or constant.
class ServerConfig {
  // Mutable static field
  static int connectionCount = 0;

  // Read-only static field (runtime evaluated)
  static final DateTime startTime = DateTime.now();

  // Compile-time constant static field
  static const int maxRetries = 5;
}

Initialization Behavior

Dart static fields are lazily initialized. The initializer expression assigned to a static field is not evaluated until the field is accessed for the first time during program execution.
  1. Lazy Loading: If a static field is never accessed, its initializer is never run, and memory is not allocated for its value.
  2. Initialization Guarantee: The Dart runtime ensures that the initialization logic runs exactly once. If the field is accessed while it is being initialized (a circular dependency), a runtime error occurs.

Access Semantics

Static fields are accessed strictly through the class name. They cannot be accessed through an instance of the class.
void main() {
  // Correct access via Class Name
  ServerConfig.connectionCount++;
  print(ServerConfig.maxRetries);

  // Incorrect access (Compile-time error)
  // var server = ServerConfig();
  // print(server.connectionCount); 
}

Scope and Visibility

  • From Instance Methods: Instance methods within the class can access static fields directly or via the class name.
  • From Static Methods: Static methods can access other static fields but cannot access instance fields, as they operate without a this context.
  • this Keyword: The this keyword cannot be used to reference a static field, as this refers exclusively to the current instance context.

Constant Static Fields

To declare a compile-time constant within a class, the field must be explicitly marked with both static and const. Dart does not support instance-level const fields. If a field is declared as const inside a class without the static modifier, the compiler will issue an error.
class MathConstants {
  // Correct: Explicitly static and const
  static const double pi = 3.14159;

  // Incorrect: const instance fields are not allowed
  // const double e = 2.718; // Compile-time error
}
Master Dart with Deep Grasping Methodology!Learn More