const keyword in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

Dart provides us with two ways in which we can declare variables with fixed values. One of them is by declaring a variable with a const keyword, and the other is by declaring the variable with a final keyword.

It should be noted that both of them does provide an assurance that once a value is assigned to the variable with them, it won't change, but indeed they are slightly different from one another.

const

A variable that is declared using the const keyword cannot be assigned any other value. Also, the variable is known as a compile-time constant, which in turn means that its value must be declared while compiling the program.

Example

Consider the example shown below -

 Live Demo

void main(){
   const name = "mukul";
   print(name);

   const marsGravity = 3.721;
   print(marsGravity);
}

Output

mukul
3.721

If we try to assign any other value to any of the two variables declared above, the compiler will throw an error.

Example

Consider the example shown below -

void main(){
   const name = "mukul";
   print(name);

   name = "mayank";
   print(name);
}

Output

Error: Can't assign to the const variable 'name'.
name = "mayank";
^^^^
Error: Compilation failed.

It should also be noted that we can declare Objects at compile-time and assign them to a constant variable.

Example

Consider the example shown below −

 Live Demo

import 'dart:math';
void main(){
   const Rectangle bounds = const Rectangle(0, 0, 3, 4);
   print(bounds);
}

Output

Rectangle (0, 0) 3 x 4
raja
Published on 21-May-2021 12:38:42
Advertisements