Final and const

If you never intend to change a variable, use final or const, eitherinstead of var or in addition to a type. A final variable can be setonly once; a const variable is a compile-time constant. (Const variablesare implicitly final.) A final top-level or class variable is initializedthe first time it’s used.

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 initializer list.

Here’s an example of creating and setting a final variable:

  1. final name = 'Bob'; // Without a type annotation
  2. final String nickname = 'Bobby';

You can’t change the value of a final variable:

  1. 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 static const.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:

  1. const bar = 1000000; // Unit of pressure (dynes/cm2)
  2. const double atm = 1.01325 * bar; // Standard atmosphere

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.

  1. var foo = const [];
  2. final bar = const [];
  3. const baz = []; // Equivalent to `const []`

You can omit const from the initializing expression of a const declaration,like for baz above. For details, see DON’T use const redundantly.

You can change the value of a non-final, non-const variable,even if it used to have a const value:

  1. foo = [1, 2, 3]; // Was const []

You can’t change the value of a const variable:

  1. baz = [42]; // Error: Constant variables can't be assigned a value.

As of Dart 2.5, you can define constants that usetype checks and casts (is and as),collection if and collection for,and spread operators ( and …?):

  1. // Valid compile-time constants as of Dart 2.5.
  2. const Object i = 3; // Where i is a const Object with an int value...
  3. const list = [i as int]; // Use a typecast.
  4. const map = {if (i is int) i: "int"}; // Use is and collection if.
  5. const set = {if (list is List<int>) ...list}; // ...and a spread.

For more information on using const to create constant values, seeLists, Maps, and Classes.