What is the final keyword in Dart?

Overview

In dart, the final keyword is used to define immutable constants or objects. It is a runtime constant.

Syntax

// Without datatype
final variable_name;

// With datatype
final data_type  variable_name;

Example

The following code shows how to implement the final keyword:

void main(){
// declaring final variable
final int num = 10;
//calculating the sum and assign to variable sum
int sum = num * num;
// displaying result
print(sum);
}

Let’s try reassigning the value for variable num in the following code:

void main(){
// declaring final variable
final int num = 10;
//calculating the sum and assign to variable sum
int sum = num * num;
// displaying result
print(sum);
// reassigning variable num
num = 20;
print(num);
}

Note: If we try to reassign the variable num then it will display an error.

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources