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:
finalvariables can be assigned a value determined during program execution.constvariables 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
finalwhen the value is fixed after initialization but not known until runtime. - Use
constwhen the value is known at compile time and will never change.
Try it Yourself:
- Create a
finalvariable for the current day of the week. - Create a
constvariable for the number of months in a year. - Print both using string interpolation.