Dart final

Summary: in this tutorial, you will learn how to define constants whose values are known at runtime using the Dart final keyword.

Introduction to the Dart final variables

The const keyword allows you to define constants that are known at compile time. To define constants whose values are known at runtime, you use the final keyword with the following syntax:

final type finalVariable;Code language: PHP (php)

In this syntax, you use the final keyword, the type of the variable, and the variable name. Unlike the const keyword, you don’t need to initialize the finalVariable in the declaration immediately.

The following example shows how to declare the currentTime final variable and assign the current time returned by the DateTime.now() to it:

void main() {
  final DateTime currentTime;
  currentTime = DateTime.now();

  print(currentTime);
}Code language: PHP (php)

Once you assign a value to a final variable, you cannot reassign a value to it. For example, the following attempts to reassign a value to the currentTime final variable and causes an error:

void main() {
  final DateTime currentTime;
  currentTime = DateTime.now();

  // error
  currentTime = DateTime.utc(2022, 12, 31);

  print(currentTime);
}Code language: PHP (php)

Error:

The final variable 'currentTime' can only be set once.Code language: JavaScript (javascript)

If you declare a final variable and initialize its value immediately, you can use type inference to make the declaration shorter. For example:

void main() {
  final currentTime = DateTime.now();

  print(currentTime);
}Code language: PHP (php)

In this example, the type of the currentTime will be DateTime because its value is the result of the DateTime.now().

Dart final vs. const

The const defines constants whose values are known at compile time while the final defines the constants whose values are known at runtime.

Both const and final keywords define identifiers that can be assigned once and their values will not be changed throughout the program.

Summary

  • Use the final keyword to define constants whose values are not known at runtime.
Was this tutorial helpful ?