Open In App

Dart – Constants

Improve
Improve
Like Article
Like
Save
Share
Report

In 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 

Creating a constant using the final keyword:

The final keyword is used to hardcode the values of the variable and it cannot be altered in the future.

Syntax:

// Without datatype
final variable_name;

// With datatype
final data_type  variable_name;

Example:

Dart




main() { 
      
  // Assigning value to var1 
  // variable without datatype 
  final var1 = 12;   
  print(var1); 
       
  // Assigning value to var2 
  // variable with datatype 
  final String var2 = "GeeksForGeeks";   
  print(var2); 
}


Output:

12
GeeksForGeeks

Creating a constant using const keyword

The const keyword behaves exactly like the final keyword. The difference between final and const is that the const makes the variable constant from compile-time only.

Syntax:

// Without datatype
final variable_name;

// With datatype
final data_type  variable_name;

Example:

Dart




main() { 
      
  // Assigning value to var1 
  // variable without datatype 
  const var1 = 32;   
  print(var1); 
       
  // Assigning value to var2 
  // variable with datatype 
  const String var2 = "GeeksForGeeks but with const";   
  print(var2); 
}


Output:

32
GeeksForGeeks but with const


Last Updated : 12 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads