Variables: var, final and const
Sprout needs to remember things: the app's name, how many plants you own, when the fern was last watered. Dart gives you four ways to declare a variable, and choosing well tells the next reader, and the compiler, how that value is allowed to behave.
The rule
varmay change,finalis set once,constis fixed before running.
var plantCount = 3; // can be reassigned
final openedAt = DateTime.now(); // assigned once, at run time
const appName = 'Sprout'; // known when the code is compiled
String nickname = 'Fernie'; // explicit type, can be reassignedvarlets Dart infer the type from the first value.plantCountis anintforever, soplantCount = 'three';is an error, whileplantCount = 4;is fine.finalcan never be reassigned, but its value may come from a calculation at run time.constis stricter: the value must be computable by the compiler.const openedAt = DateTime.now();fails, because the time only exists once the app runs.
Null safety adds one more rule. A plain String can never hold null. Add ? to allow it:
DateTime? lastWatered; // starts as null, allowed
int days = null; // error: int does not accept nullThe shortcut
Ask two questions in order, and stop at the first yes.
Is the value written in the source and never changes?
The default interval of 7 days is. Use
const defaultDays = 7;
Prefer final over var when in doubt. Most values in a Flutter app never change after they are created, and final makes accidental reassignment impossible.
Drills
Answer fast — trust the rule.
What happens with var count = 3; count = 'three';?
Which declaration is an error?
What is the value of int? days; before anything is assigned?
A plant's name is loaded from storage and must never change afterwards. Best declaration?
Remember
varmay change,finalis set once,constis fixed before running.- Ask: written in source?
const. Set once?final. Otherwisevar. Might be missing? add?. - Trap:
constwith a run-time value, and assigningnullto a type without?.
