The const
and final
keywords declare constants values in Dart that can't be changed after initializing them. However, the main difference lies in their time of evaluation. const
variables are evaluated at compile-time while final
variables are evaluated at run-time.
const
keywordThe const keyword is used to declare variables whose values are known and fixed at compile-time and are
// Without datatype
const variable_name;
// With datatype
const data_type variable_name;
// Varibale Declarationconst int count = 5;const double PI = 3.14159;// Main Function to executevoid main() {print(count);print(PI);}
In the code above, we declare count
and PI
as const
variables with assigned values known at compile-time. Once set, their values cannot be changed. Using const
can help optimize memory usage and improve performance in specific scenarios.
final
keywordFinal variables are evaluated at runtime when they are assigned a value, then it also becomes immutable.
// Without datatype
final variable_name;
// With datatype
final data_type variable_name;
// Varibale Declarationfinal String name = 'John';final int temperature = 23;// Main Function to executevoid main() {print(name);print(temperature);}
In the code above, we declare name
and temperature
as final
variables. They can be assigned values at runtime but cannot be modified afterward. final
variables are helpful when we need to set a value dynamically but want to ensure it remains constant throughout the execution.
To better understand the difference between const
and final
keywords, consider the following example:
void main() {final int finalValue = DateTime.now().year;const int constValue = DateTime.now().year;}
In this example, finalValue
is evaluated at runtime and assigned the current year value using DateTime.now().year
. The value remains constant once assigned.
On the other hand, constValue
is evaluated at compile-time, meaning it receives the value known at compilation time. It is inappropriate to assign values that can only be determined at runtime. An error will be generated at line 3 when we click the run button because we can't assign a runtime value to const
variable.
We can best summarize the differences between the const
and final
keyword in the table below.
Keyword | Evaluation Time | Immutability |
| Compile-time | Immutable |
| Run-time | Immutable |
Free Resources