What are the basic variable declaration keywords in Dart, specifically var, final, and const, and how do they differ from each other?
Short answer
The var keyword declares a variable whose value can be reassigned later, with Dart automatically inferring its specific type based on the initial assigned value, final declares a variable that can only ever be assigned its value exactly once, though that assignment can happen at…
Advertisement
AModel answer
The var keyword declares a variable whose value can be reassigned later, with Dart automatically inferring its specific type based on the initial assigned value, final declares a variable that can only ever be assigned its value exactly once, though that assignment can happen at runtime, and const declares a genuinely compile time constant, meaning its value must be fully known and fixed at compile time itself, and choosing the most restrictive appropriate option among these three, generally preferring const or final over var whenever reasonably possible, helps prevent accidental, unintended reassignment mistakes.
var count = 5; // Can be reassigned
final name = 'Alex'; // Assigned once, but value determined at runtime
const pi = 3.14159; // Fixed at compile timeReal-world example
A developer declares a widget's fixed padding value using const specifically because that exact value will never change, allowing Dart's compiler to optimize that specific value more efficiently than if it had been declared using var.
Likely follow-ups
- What happens if you try to reassign a value to a variable declared with final?
- When would you use var instead of always simply preferring final?
Related topics