Understanding var, final, and const in Dart

1. var

Definition: A var variable is mutable (can change) and its type is inferred automatically.

var name = 'Rakesh';
name = 'Amit'; // ✅ allowed

2. final

Definition: final variables are assigned only once. The value is determined at runtime and can't be changed later.

final city = 'Delhi';
city = 'Mumbai'; // ❌ Error: Final variable can't be reassigned
Use final when the value won’t change and is known only at runtime.

3. const

Definition: const variables are compile-time constants. Their values must be known and fixed when the code is compiled.

const country = 'India';
country = 'Nepal'; // ❌ Error: Const variable can't be reassigned
Use const when the value never changes and is known at compile time.

4. Difference Between final and const

Aspect final const
Mutability Immutable (can’t change after assigning) Immutable (must be constant from start)
Evaluated At runtime At compile-time
Use Case Value known only at runtime Value known at compile time
Example final today = DateTime.now(); const pi = 3.14;
void main() {
  final timestamp = DateTime.now(); // ✅ valid
  // const timestamp = DateTime.now(); ❌ invalid - not compile-time constant

  const appName = 'MyApp'; // ✅ valid
  print(timestamp);
  print(appName);
}

5. Reference Links