---
title: "Grouping Related Behavior with Static Members and Constants in Dart"
date: "2026-12-03T10:09:00+07:00"
description: "Static variables, static const, and static methods group class-wide state in Dart — learn lazy init, const interplay, and when top-level wins."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/dart-static-members-constants.jpg"
alt: "Conceptual illustration of related constants and shared functions grouped together inside one container"
tags: ['dart', 'dart-language', 'oop', 'static-members', 'constants']
---

Sometimes the thing you are modeling is not an object but a *kind* of object — and Dart's `static` keyword gives you a place to hang the shared state, constants, and helpers that belong to the type itself rather than to any one instance.

## Static variables hold class-wide state

Use the `static` keyword for class variables: state and constants that belong to the class rather than to any single instance. Dart initializes them **lazily** — a static variable is not evaluated until it is first used, which makes deferred setup essentially free:

```dart
class Config {
  static final Map<String, String> defaults = _loadDefaults();
  static Map<String, String> _loadDefaults() {
    print('loading defaults...');
    return {'theme': 'dark', 'locale': 'en'};
  }
}

void main() {
  print('before first use');
  print(Config.defaults['theme']); // loads, then prints dark
}
```

Nothing happens until `Config.defaults` is touched, so the cost is paid only by programs that actually use the member — a heavy `static final` on an optional code path costs the rest of the program nothing at startup. Remember the flip side, though: once initialized, a static variable lives for the rest of the isolate's life and is shared by every caller — there is exactly one copy, no matter how many objects or tests touch it.

## static const: compile-time constants

When the value is known at compile time, promote the static to `const`. Effective Dart's style guide asks for `lowerCamelCase` names on constants, and the core libraries follow the same convention. Because a `static const` is a compile-time constant, it can serve as a default parameter value and live in any other constant context:

```dart
class Queue {
  static const initialCapacity = 16;
  Queue({this.capacity = initialCapacity});
  final int capacity;
}

void main() {
  print(Queue.initialCapacity); // 16
}
```

Constants also pair naturally with `const` constructors: a value like `Queue.initialCapacity` can appear in a canonicalized `const` object, where two identical constructions share one instance — the interplay covered in `dart-classes-constructors-initializing-formals.md`. And because the value is fixed for the whole program, the compiler stores it once and reuses it everywhere it appears, with no allocation and no initialization order to reason about.

## Static methods have no `this`

Static methods do not operate on an instance, so they have no access to `this` — but they *can* read and write static state, and you invoke them directly on the class:

```dart
import 'dart:math';

class Point {
  double x;
  double y;
  Point(this.x, this.y);
  static double distanceBetween(Point a, Point b) {
    final dx = a.x - b.x;
    final dy = a.y - b.y;
    return sqrt(dx * dx + dy * dy);
  }
}

void main() {
  print(Point.distanceBetween(Point(2, 2), Point(4, 4))); // 2.8284271247461903
}
```

`distanceBetween` takes both points as arguments because a static method belongs to `Point` the *type*, not to either instance. The same rule makes static methods usable as compile-time constants: you can pass a static method tear-off directly to a `const` constructor, as `const rule = Rule(Rule.isNotEmpty)` does when `Rule` declares `static bool isNotEmpty(String value) => value.isNotEmpty;` and `const Rule(this.test);`.

## When top-level declarations beat statics

Here is the guideline most Dart newcomers miss: **consider using top-level functions instead of static methods** for common or widely used utilities. Dart does not force every definition inside a class, and Effective Dart goes further with **AVOID defining a class that contains only static members** (`avoid_classes_with_only_static_members`):

```dart
// Good: top-level, no ceremony.
DateTime mostRecent(List<DateTime> dates) =>
    dates.reduce((a, b) => a.isAfter(b) ? a : b);
const favoriteMammal = 'weasel';

// Bad: a class that exists only as a filing cabinet.
class DateUtils {
  static DateTime mostRecent(List<DateTime> dates) =>
      dates.reduce((a, b) => a.isAfter(b) ? a : b);
}
```

In idiomatic Dart, classes define *kinds of objects*, and a type that is never instantiated is a code smell — a "namespace" class is what import prefixes and libraries are for. Use this decision table to route each case:

| Situation | Prefer |
| --- | --- |
| Logic that genuinely belongs to a type or needs its private members | `static` member |
| A general utility with no relationship to a class | Top-level function |
| A constant tied to a type (`Queue.initialCapacity`) | `static const` |
| Grouping purely to dodge name collisions | A library with an import prefix |
| Related fixed choices like colors or statuses | `static const` in a class, or an `enum` |

There is one recognized exception to the "no filing cabinets" rule: grouping related constants in a class reads well precisely because the values are a fixed, meaningful set — `class Color { static const red = '#f00'; static const green = '#0f0'; }` — and the same instinct makes an `enum` the right tool for a closed set of cases.

## Statics are global: the singleton and its pitfalls

The most common legitimate use of mutable static instance state is the singleton, built from one private constructor and one static instance:

```dart
class AppConfig {
  static final AppConfig instance = AppConfig._();
  AppConfig._();
  String locale = 'en';
}

void main() {
  AppConfig.instance.locale = 'th';
  print(AppConfig.instance.locale); // th
}
```

Every caller shares that one object, which is exactly the power — and the danger. Any code anywhere can mutate `AppConfig.instance` or any static variable, so ordering bugs migrate silently into your codebase, and static state persists between tests: a static initialized in one test is still initialized in the next, so tests that assume a clean slate will flake. Reset it explicitly in `setUp`, or inject the state instead of hiding it in a static. If the value is immutable, both problems disappear — another reason `static const` is the default choice and mutable statics are the exception.

## Takeaways

- `static` members belong to the class: no `this`, invoked directly on the type, and static variables initialize lazily on first use.
- Prefer `static const` (in `lowerCamelCase`) for anything compile-time — it unlocks constant contexts, default parameters, and canonicalized instances.
- Static methods can be compile-time constants, so their tear-offs can be passed straight into `const` constructors.
- Reach for top-level functions and libraries before creating a class that contains only static members, and keep mutable static state rare and isolated.
- **Takeaway:** group by meaning, not by habit — statics and constants belong to a type, while anything that is not about a type belongs at the top level of a library.

## References

- https://dart.dev/language/classes
- https://dart.dev/effective-dart/design
- https://dart.dev/effective-dart/usage
