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.