What is the difference between const and final keyword in dart?

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 keyword

The const keyword is used to declare variables whose values are known and fixed at compile-time and are immutableVariables with values that cannot be changed once initialized ensuring their constant and unmodifiable nature..

Syntax

// Without datatype
const variable_name;

// With datatype
const data_type variable_name;

Code example

// Varibale Declaration
const int count = 5;
const double PI = 3.14159;
// Main Function to execute
void 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 keyword

Final variables are evaluated at runtime when they are assigned a value, then it also becomes immutable.

Syntax

// Without datatype
final variable_name;

// With datatype
final data_type variable_name;

Code example

// Varibale Declaration
final String name = 'John';
final int temperature = 23;
// Main Function to execute
void 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.

Difference with a common example

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.

Error generated while assigning value to const variable during runtime
Error generated while assigning value to const variable during runtime

Conclusion

We can best summarize the differences between the const and final keyword in the table below.

Keyword

Evaluation Time

Immutability

const

Compile-time

Immutable

final

Run-time

Immutable

Copyright ©2024 Educative, Inc. All rights reserved