Dart Data Types

Dart Constants

Since the Dart Constant is specified as an immutable object, it cannot be altered while the program is running. It is not possible to change the value once it has been initialized to the constant variable.

Defining/Initializing Constant in Dart

There are two definitions for the Dart constant.

  • Using the final keyword
  • Using the const keyword

It is useful when we wish to maintain the value throughout the entire program. To construct a constant variable, use the terms final and const. The data-type is used in combination with the keywords final and const. If we attempt to change the constant variable, Dart will raise an exception.

The compile-time constant is represented by a const keyword, and the final variable can only be set once.

Define Constant Using final Keyword

The last term allows us to define the constant. Below is the syntax.

Syntax

				
					final const_name;  
or   
final data_type const_name  
				
			

Example

				
					void main () {  
  final a = 10;  
  final b = 20;  
    
 print(a);  
 print(b);  
}  
				
			

Output

				
					10
20
				
			

Define Constants Using const Keyword

The const keyword allows us to define constants. Below is the syntax.

Syntax

				
					const const_name  
Or  
const data_type const_name  
				
			

Example

				
					void main() {  
   const name= "Peter";  
   print(name);  
}  
				
			

Output

				
					Peter
				
			
Share this Doc

Dart Constants

Or copy link

Explore Topic