Constants

suggest change

In Dart, immutability is supported at both runtime and compile time through the final and const keywords. Choosing the right modifier optimizes memory usage, enables compile-time verification, and dramatically reduces UI rebuild overhead in Flutter applications.


final vs const

While both final and const declare variables that cannot be reassigned, their initialization lifecycles are fundamentally different:

Feature final const
Initialization At runtime (when first accessed) At compile time
Value Known Can be computed dynamically (e.g., DateTime.now()) Must be known ahead of time
Object Immutability Shallow (reference is fixed, object may mutate) Deep immutability (all fields and elements are frozen)
Memory Allocation New instance allocated on heap unless cached Canonicalized (single shared instance in memory)
void main() {
  // final: computed dynamically at runtime
  final currentTime = DateTime.now();
  final randomValue = 10 + 5;

  // const: must be known and fixed at compile time
  const maxRetries = 3;
  const timeoutMs = 1000 * 30; // 30,000

  // Compile Error: Cannot evaluate DateTime.now() at compile time
  // const invalidTime = DateTime.now();
}

const Collections and Deep Immutability

When you declare a collection with const, the entire collection and all of its elements become deeply immutable:

void main() {
  // final list: reference cannot change, but items CAN be modified
  final mutableList = [1, 2, 3];
  mutableList.add(4); // Allowed!
  print(mutableList); // [1, 2, 3, 4]

  // const list: deeply immutable
  const frozenList = [1, 2, 3];
  // frozenList.add(4); // Throws UnsupportedError (Cannot add to an unmodifiable list)

  // const Map
  const httpHeaders = {
    'Accept': 'application/json',
    'User-Agent': 'DartClient/1.0',
  };
  // httpHeaders['Accept'] = 'text/html'; // Throws UnsupportedError
}

const Constructors and Canonicalization

A class can provide a const constructor if all of its instance variables are final:

class ThemeConfig {
  final String primaryColor;
  final int fontSize;

  // All fields must be final to allow a const constructor
  const ThemeConfig({required this.primaryColor, required this.fontSize});
}

void main() {
  // Both point to the exact same canonical instance in memory
  const lightThemeA = ThemeConfig(primaryColor: '#FFFFFF', fontSize: 14);
  const lightThemeB = ThemeConfig(primaryColor: '#FFFFFF', fontSize: 14);

  print(identical(lightThemeA, lightThemeB)); // true
}

Why Canonicalization Matters for Flutter

In Flutter, widgets with const constructors are compiled down to a single persistent instance. During widget tree rebuilding, the framework identifies const widgets using referential identity (identical(oldWidget, newWidget)), completely skipping widget rebuilds and layout recalculations.


Compile-Time Environment Constants

Dart can read build-time environment declarations passed via -D (--define) command-line flags (Flutter uses --dart-define):

void main() {
  // Pass via: dart run -DAPI_URL=https://api.prod.com -DDEBUG_MODE=true main.dart
  const apiUrl = String.fromEnvironment('API_URL', defaultValue: 'https://api.dev.com');
  const isDebug = bool.fromEnvironment('DEBUG_MODE', defaultValue: false);
  const port = int.fromEnvironment('PORT', defaultValue: 8080);

  print('Target API: $apiUrl');
  print('Debug mode: $isDebug');
  print('Server Port: $port');
}

static const Class Constants

To define constants tied to a class namespace rather than a particular instance, use static const:

class AppLimits {
  // Belongs to the class type, allocated only once
  static const int maxUploadSizeMb = 50;
  static const Duration networkTimeout = Duration(seconds: 15);
  static const String apiVersion = 'v2';

  // Private constructor prevents instantiation
  AppLimits._();
}

void main() {
  print('Max upload size: ${AppLimits.maxUploadSizeMb} MB');
  print('Timeout: ${AppLimits.networkTimeout.inSeconds}s');
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents