What is dart constants and when we use it?

Dart language, Constants are objects whose values cannot be changed during the execution of the program. Hence, they are a type of immutable object. A constant cannot be reassigned any value if a value has been assigned to it earlier. If we try to reassign any value to a constant, Dart throws an exception.

In Dart language, we can define constants by using 2 keywords :

  • final keyword
  • const keyword

Final Keyword In Dart
The final keyword is used to hardcode the values of the variable and it cannot be altered in future, neither any kind of operations performed on these variables can alter its value (state).

// Without datatype
final variable_name;

// With datatype
final data_type  variable_name;
void main() {

// Assigning value to geek1
// variable without datatype
final fever = "flutterfever.com";

// Printing variable
print(fever);
	
// Assigning value to fever2
// variable with datatype
final String fever2 = "flutterfever.com2!!";

// Printing variable fever2 
print(fever2 );
}

Const Keyword in Dart
The Const keyword in Dart behaves exactly like the final keyword. The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object, makes the object’s entire deep state strictly fixed at compile-time and that the object with this state will be considered frozen and completely immutable.

It’s important to notice that a constant only accepts a value that is truly constant at compile time. For example, the following will result in an error:

void main() {
  const currentTime = DateTime.now();
  print(currentTime);
}

n this example, the DateTime.now() returns the current time.

The program attempts to define a constant and assigns the current time returned by the DateTime.now() to the currentTime constant.

However, the value of the DateTime.now() can be determined only at runtime, not compile time. Therefore, the Dart compiler issues an error.

To fix this, you need to declare the variable as final like this:

void main() {
  final currentTime = DateTime.now();
  print(currentTime);
}
  • Summary
  • A constant is an identifier whose value doesn’t change.
  • Use the const keyword to define a constant.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More