Question #289EasyDart BasicsImportant

What is the use of static vs final vs const ? in flutter when to use which ?

#flutter

Answer

Overview

text
static
,
text
final
, and
text
const
are three different modifiers in Dart Flutter that control scope, mutability, and when the value is computed.


static -- Class-Level (Not Instance)

text
static
belongs to the class itself, not any specific instance. Shared across all instances.

dart
class Counter {
  static int totalCount = 0;   // Shared across ALL instances
  int instanceCount = 0;       // Per-instance

  void increment() {
    totalCount++;       // Class-level
    instanceCount++;    // Instance-level
  }

  static void resetAll() {
    totalCount = 0; // Static method -- only accesses static members
  }
}

final c1 = Counter()..increment()..increment();
final c2 = Counter()..increment();

print(Counter.totalCount); // 3 -- shared across all
print(c1.instanceCount);   // 2 -- c1 only
print(c2.instanceCount);   // 1 -- c2 only

final -- Runtime Constant (Set Once)

text
final
is set once and cannot be reassigned. Value can be determined at runtime.

dart
class Config {
  final String apiUrl;      // Set in constructor, then fixed
  final DateTime createdAt; // Runtime value -- not known at compile time

  Config(this.apiUrl) : createdAt = DateTime.now();
}

// final local variable
final user = await fetchUser();  // Runtime value, set once
final count = items.length;      // Computed at runtime

const -- Compile-Time Constant

text
const
must be known at compile time. Created once, deeply immutable, cached.

dart
const pi = 3.14159;
const maxRetries = 3;
const appName = 'MyApp';

class AppColors {
  static const primary = Color(0xFF6200EE);     // compile-time
  static const secondary = Color(0xFF03DAC6);
}

// const widget -- Flutter reuses same object (performance!)
const SizedBox(height: 16);
const Text('Hello');

// const list -- deeply immutable
const tags = ['flutter', 'dart']; // Cannot add/remove

Combined Usage in a Class

dart
class ApiService {
  // static const -- class-level, compile-time, shared
  static const String baseUrl = 'https://api.example.com
  static const int timeout = 30;

  // static -- class-level, mutable
  static int requestCount = 0;

  // final -- instance-level, set once at runtime
  final String authToken;
  final DateTime initializedAt;

  ApiService(this.authToken) : initializedAt = DateTime.now();

  Future<void> get(String endpoint) async {
    requestCount++;  // Shared count across all instances
    // ...
  }
}

// Usage
print(ApiService.baseUrl);      // static const
ApiService.requestCount++;      // static (mutable)
final api = ApiService('token');
print(api.authToken);           // final (instance)

Decision Guide

UseWhen
text
const
Compile-time known value (literals, colors, strings) -- always widget performance
text
final
Runtime value set once (from API, constructor, DateTime)
text
static
Shared across all instances (counters, caches, helpers)
text
static const
Class-level compile-time constant (API URLs, config)
text
static final
Class-level singleton initialized at runtime

Quick Comparison

Feature
text
static
text
final
text
const
LevelClassInstanceEither
Can reassignYes (unless final)NoNo
When setAny timeOnce (runtime OK)Compile-time
Deeply immutableNoNoYes
Widget perfNoNoYes

Flutter Rule: Prefer

text
const
for widgets and values. Use
text
final
for runtime values. Use
text
static
for shared class utilities. Combine:
text
static const
for constants shared at class level.