Constants in Dart

Constants are variables whose values cannot be changed once assigned. Dart provides two main keywords for constants:

  • final – Value is set once at runtime and cannot be reassigned.
  • const – Value is set at compile time and must be known at compile time.

Difference Between final and const:

  • final variables can be assigned a value determined during program execution.
  • const variables must be assigned a compile-time constant.

Example:

void main() {
  final currentYear = DateTime.now().year; // Assigned at runtime
  const pi = 3.1416;                       // Compile-time constant

  print('Current Year: $currentYear');
  print('Value of Pi: $pi');
}

Notes:

  • Use final when the value is fixed after initialization but not known until runtime.
  • Use const when the value is known at compile time and will never change.

Try it Yourself:

  • Create a final variable for the current day of the week.
  • Create a const variable for the number of months in a year.
  • Print both using string interpolation.