Const keyword in Dart

What are constant variables?

The const keyword is to declare a variable, if you never intend to change the value.

const variables are compile-time constants.

There are multiple ways to declare const variable:

  1. constant local variable.
  2. constant class variable.
  3. constant library variable.

Constant local variable

The variable declaration within the functions are called local variable, add const keyword before the local variable to mark its as constant.

The following code snippet shows how to declare a const variables.

main() {
  // const local variable without type
  const movie1 = 'Iron man';

  // const local variable with explicitly type
  const String movie2 = 'Iron man 2';
}

Constant class variable

The variable declaration within the class, add const keyword before the instance variable to mark it as constant.

If the const variable is at the class level, mark it static const:

Note: The modifier 'static' should be before the modifier 'const'.

The following code snippet shows how to declare const class variable and access.

class Product {
  static const double discount = 5.0;
}

main() {
  // Access the static variable using class
  // print to console
  print(Product.discount);
}

Arithmetic operation on constant numbers

You can also set the value of const variable to the result of an arithmetic operation on constant numbers:

The following code snippet shows how to apply arithmetic operations on constant numbers.

class Product {
  static const double discount = 5.0;
}

main() {
  // set the value to the result of an arithmetic operation on constant numbers:
  const double cashback = Product.discount * 2.0;

  print(cashback);
}

Create constant values

The const keyword isn’t just for declaring constant variables. You can also use it to create constant values:

The following code snippet shows how to create constant values.

// create constant values
  var movies = const ['Iron Man', 'Avengers', 'Real Steel'];

Constructors that create constant values

You can also use const to create constant constructor to create constant values:

The following code snippet shows how to define constant constructor to create constant values.

class Movie {
  final int id;
  final String name;

  // Define const constructor using const keyword
  // Const constructors can't have a body.
  const Movie(this.id, this.name);
}

main(List<String> args) {
  // Create an instance and pass values
  var movie = Movie(100, 'Iron man');

  // print to console
  print('${movie.id} ${movie.name}'); // 100 Iron man
}

Omit const from the initializing expression

You can omit const from the initializing expression of a const declaration:

const movies =  ['Iron Man', 'Avengers', 'Real Steel'];

Change the value

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

var movies = const [];

  movies = ['Iron man', 'Avengers', 'Real Steel'];