Sobes.tech
Junior

What is the difference between immutability of final and const in Dart?

sobes.tech AI

Answer from AI

The main difference is as follows:

  • final: A variable marked as final can only be initialized once. Its value is determined at runtime and cannot be changed after assignment.
void main() {
  final int myFinalValue = 10; // Initialized at runtime during creation
  // myFinalValue = 20; // Error: Cannot assign a new value to a final variable
  print(myFinalValue);
}
  • const: A variable marked as const is a compile-time constant. Its value must be known at compile time and cannot be changed later. Objects marked as const are created only once and shared.
void main() {
  const int myConstValue = 5; // Value known at compile time
  // myConstValue = 15; // Error: Cannot assign a new value to a const variable
  print(myConstValue);

  const List<int> constList = [1, 2, 3]; // const list - immutable
  // constList.add(4); // Error: Cannot modify a const list
}

Here is a brief summary of the differences:

Characteristic final const
Initialization At runtime At compile time
Mutability of value Immutable after assignment Immutable
Time of definition Runtime Compile-time
Object creation Each time code runs Once, shared among uses
Applicability For variables and class members For variables and values
What is the difference between immutability of final… - sobes.tech