An assignment statement in Dart follows the same grammar as other languages in the C language family:
// (optional modifier) (optional type) variableName = value;
final String name = 'Donald'; //final modifier, String type
First, you can optionally declare a variable as either var, final, or const, like so:
var animal = 'Duck';
final numValue = 42;
const isBoring = true;
These modifiers indicate whether the variable is mutable. var is completely mutable as its value can be reassigned at any point. final variables can only be assigned once, but by using objects, you can change the value of its fields. const variables are compile-time constants and are fully immutable; nothing about these variables can be changed once they've been assigned.
Please note that you can only specify a type when you're using the final modifier, as follows:
final int numValue = 42; // this is ok
// NOT OK: const int or var int.
After the final modifier, you can optionally declare the variable type, from simple built-in types such as int, double, and bool, to your own more complex custom types. This notation is standard for languages such as Java, C, C++, Objective-C, and C#.
Explicitly annotating the type of a variable is the traditional way of declaring variables in languages such as Java and C, but Dart can also interpolate the type based on its assignment. In the typeInterpolation example, we decorated the types with the var keyword; Dart was able to figure out the type based on the value that was assigned to the variable. For example, 15 is an integer, while 27.6 is a double. In most cases, there is no need to explicitly reference the type; the compiler is smart enough to figure this out. This allows us, as developers, to write succinct, script-like code and still take advantage of inherent gains that we get from a type-safe language.
The difference between final and const is subtle but important. A final variable must have a value assigned to it in the same statement where it was declared, and that variable cannot be reassigned to a different value:
final meaningOfLife = 42;
meaningOfLife = 64; // This will throw an error
While the top-level value of a final variable cannot change, its internal contents can. In a list of numbers that have been assigned to a final variable, you can change the internal values of that list, but you cannot assign a completely new list.
const takes this one step further. const values must be determined at compile time, new values are blocked from being assigned to const variables, and the internal contents of that variable must also be completely sealed. Typically, this is indicated by having the object have a const constructor, which only allows immutable values to be used. Since their value is already determined at compile time, const values also tend to be faster than variables.