Skip to content

Difference between Const and Final in Dart

In Dart, final and const are both used to declare variables that cannot be reassigned once they are initialized. However, there are some differences between them

  1. Mutability
    • final variables can only be assigned once. Their value can be set at runtime and is evaluated when assigned.
    • const variables are implicitly final but are compile-time constants. They are constants at compile time, meaning their value must be known and set during compilation. This often means that they are used with values that are known at compile time.
  2. Initialization
    • final variables can be initialized at runtime. For example, the result of a function call or a value is determined based on conditions.
    • const variables must be initialized with a constant value. This can be a literal value (e.g., const int x = 5;) or a const constructor (e.g., const MyClass()).

Here are some examples to illustrate the differences:

// final variable
final int finalVar;
finalVar = 10; // This is valid if finalVar hasn't been assigned before.

// const variable
const int constVar = 5; // Initialization with a constant value.

// const variable with expression
final currentTime = DateTime.now();
const compileTime = DateTime(2023, 11, 29); // Won't work as DateTime.now() isn't known at compile time.

In summary, final is for immutable variables whose values can be determined at runtime and set once, while const is for compile-time constants whose values must be known at compile time and are, therefore, more restrictive in their usage.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments