Difference between the “const” and “final” keywords in Dart

CodeWithFlutter
2 Min Read

The const and final keywords in Dart are used to declare variables that cannot be reassigned after they have been initialized. However, there is a subtle difference between the two keywords:

  1. const: The const keyword is used to declare variables that are compile-time constants. This means that the value of a const variable must be known at compile time and cannot be changed during runtime. In addition, const variables are implicitly final and must be set to a value that is also a const, such as a string, number, or constant expression.
  2. final: The final keyword is used to declare variables that are runtime constants. This means that the value of a final variable can be set at runtime, but cannot be changed after it has been initialized. Unlike const variables, final variables can be set to values that are not const, such as the result of a function call or a user-input value.

In general, you should use the const keyword when you need to declare a value that must be constant at compile time and the final keyword when you need to declare a value that can be set at runtime but cannot be changed after it has been initialized. If you are not sure which keyword to use, it is usually safe to use final.

Share this Article
Leave a comment