Difference Between var, final, and const in Dart

In Dart, var, final, and const are keywords used to declare variables, but they serve different purposes and have distinct behaviors. Understanding these differences is crucial for effective Dart programming.

1. var

The var keyword is used to declare a variable with type inference. This means that the Dart compiler determines the type of the variable based on the assigned value. A variable declared with var can be reassigned to a value of the same type.

void main() {
var name = 'Alice'; // Dart infers the type as String
print('Name: $name');

name = 'Bob'; // Reassigning to another String
print('Updated Name: $name');

// You can also reassign to a value of the same type
var age = 30; // Dart infers the type as int
age = 31; // This is allowed
print('Updated Age: $age');
}

2. final

The final keyword is used to declare a variable that can only be assigned once. Once a value is assigned to a final variable, it cannot be changed. This is useful for constants that are determined at runtime.

void main() {
final age = 30; // Dart infers the type as int
print('Age: $age');

// Uncommenting the next line will cause an error
// age = 31; // Error: The final variable 'age' can only be set once

final List<string> fruits = ['Apple', 'Banana'];
fruits.add('Cherry'); // This is allowed because the list itself is mutable
print('Fruits: $fruits');
}
</string>

3. const

The const keyword is used to declare compile-time constants. A variable declared with const must be assigned a value that is known at compile time, and it cannot be changed. This is useful for defining constants that are used throughout your application.

void main() {
const pi = 3.14; // Compile-time constant
print('Value of Pi: $pi');

// Uncommenting the next line will cause an error
// pi = 3.14159; // Error: Constant variables can't be assigned a value

const List<string> colors = ['Red', 'Green', 'Blue'];
// colors.add('Yellow'); // Error: Cannot add to an unmodifiable list
print('Colors: $colors');
}
</string>

4. Summary of Differences

  • Reassignment:
    • var: Can be reassigned to a new value of the same type.
    • final: Can only be assigned once; cannot be reassigned.
    • const: Must be assigned a compile-time constant; cannot be reassigned.
  • Mutability:
    • var: Can be mutable or immutable based on the type.
    • final: The variable itself is immutable, but the object it points to can be mutable.
    • const: The variable and the object it points to are both immutable.

Conclusion

In summary, var, final, and const are essential keywords in Dart for variable declaration, each serving a unique purpose. Understanding when to use each keyword will help you write more efficient and maintainable Dart code.