Dart Variables: var, final, and const
In Dart, `var` creates a mutable variable, while `final` and `const` are for single-assignment. Use `var` for changing state, `final` for runtime values set once, and `const` for compile-time constants. The footgun is confusing `final` with `const`.
WHY IT EXISTS: Dart needs a way to manage both mutable state and immutable values. Differentiating between values that change (var), values set once at runtime (final), and values known before the program even runs (const) allows for safer, more performant code by enforcing immutability where appropriate.
THE MENTAL MODEL: Think of variables as labeled boxes. A var box can have its contents swapped out anytime. A final box gets its contents once when it's created, then is sealed shut at runtime. A const box is sealed at the factory (compile time) before the program even starts, and its value can never change.
HOW IT WORKS: The keyword you choose determines a variable's mutability. First, var declares a variable whose type is inferred and whose value can be reassigned: var count = 0; count = 1; is valid. Second, final declares a variable that must be initialized and can never be reassigned. Its value can be computed at runtime: final name = someFunction();. Third, const declares a compile-time constant. The value must be known before the code runs, like const pi = 3.14;. All const variables are implicitly final.
WHEN TO USE IT: Prefer const for values that are truly constant, like padding amounts or color codes, to get performance benefits. Use final for class members that are initialized once via a constructor or for values you receive from an API call that shouldn't change. Use var for local variables inside methods where state needs to change, like a loop counter.
WHEN NOT TO USE IT: Don't use var for values that should be immutable after initialization; use final or const for safety. Don't use const for any value that is calculated at runtime, such as DateTime.now() or the return value of a non-constant function; use final instead. Avoid using final for simple, mutable local variables where var is clearer.
ONE CANONICAL EXAMPLE: In a Flutter widget, you might declare a const for a padding value: const padding = 16.0;. You would use final for a property passed into the widget's constructor: final String title;. Inside a stateful widget's method, you might use var for a temporary calculation: var total = price * quantity;.
Read the original → dart.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.