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 null