final keyword in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

The final keyword in Dart is used to create constants or objects that are immutable in nature. The only difference between the final and const keyword is that final is a runtime-constant, which in turn means that its value can be assigned at runtime instead of the compile-time that we had for the const keyword.

Example

Consider the example shown below −

 Live Demo

void main(){
   final int xy = 10;
   print(xy);
}

Output

10

In the above example, we declared an int variable with a final keyword, which means that the value once assigned to it won't change.

Example

Consider the example shown below −

void main(){
   final int xy = 10;
   print(xy);
   xy = 99;
   print(xy);
}

Output

Error: Can't assign to the final variable 'xy'.
   xy = 99;
   ^^
Error: Compilation failed.

Like any normal variable in Dart, the variable declared with the final keyword can also infer the type of data it is going to store with the help of dartAnalyzer.

Example

Consider the example shown below −

 Live Demo

void main(){
   final name = "tutorialspoint";
   print(name);
}

Output

tutorialspoint

Now let's have a look at the case where the value is evaluated at runtime.

Example

Consider the example shown below −

 Live Demo

void main(){
   final squareOfTwo = getSquareOfNumber(2);
   print("SqaureOfTwo = $squareOfTwo");
}

num getSquareOfNumber(num i){
   return i * i;
}

In the above example, we have the main function inside which the final constant is getting its value from a function that will be evaluated at runtime and not compile-time.

Output

SqaureOfTwo = 4
raja
Published on 21-May-2021 12:43:37
Advertisements