Dart Const and Final, what is the Difference

Dart has two types of constant values: const is constant from compile-time and final has a constant value in run-time.

While programming any software, there is always, needed some values to have a fixed value that can not be changed once assigned the value.

Dart provides two keywords for defining constant values const and final.

Developers from Javascript background must know the const keyword to declare constant values and Java Developer must know the final keyword to define Constant values.

const String baseUrlGithub = 'https://github.com/';
final String baseUrlMedium = 'https://medium.com/';

It seems interesting to see that Dart provides two keywords to define the constant value, both of these basic usages are the same to define the constant value, this way they look the same but they are not the same. Let’s look into both const and final to know the exact difference and usage.

final

  • A value can be assigned only once.
  • final is the run-time constant value. It means after compiling executable code these constant values are created.
  • Final values are redefined when tree structures rebuild themselves or a build method is called. For example on setState final values are redefined.
  • Final variables can be defined in a class or function of Dart language.
  • Usage: use a final keyword to define constant values When we don’t know the exact value at compile-time, for example, data received from backend over API

const

  • A value can be assigned only once.
  • A const is a compile-time constant, meaning it is defined and has a constant value at compile-time and the same value is used in runtime.
  • const values remain the same when tree structures rebuild themselves or a build method is called. For example, setState const values remain the same.
  • Const value can not be defined in a class but can be defined in a function.
  • Usage: when we are sure that this value will not be changed during run time, use the const keyword to define constant value, for example, app colors, base API URL, etc.

Flutter Developer