Note: Instance variables can be final
but not const
. Final instance variables must be initialized before the constructor body starts — at the variable declaration, by a constructor parameter, or in the constructor’s .
Here’s an example of creating and setting a final variable:
name = 'Alice'; // Error: a final variable can only be set once.
Use const
for variables that you want to be compile-time constants. Ifthe const variable is at the class level, mark it .Where you declare the variable, set the value to a compile-time constantsuch as a number or string literal, a constvariable, or the result of an arithmetic operation on constant numbers:
The const
keyword isn’t just for declaring constant variables.You can also use it to create constant values,as well as to declare constructors that create constant values.Any variable can have a constant value.
final bar = const [];
You can change the value of a non-final, non-const variable,even if it used to have a const value:
You can’t change the value of a const variable:
baz = [42]; // Error: Constant variables can't be assigned a value.
For more information on using const
to create constant values, seeLists, , and Classes.