In dart, the final
keyword is used to define immutable constants or objects. It is a runtime constant.
// Without datatype
final variable_name;
// With datatype
final data_type variable_name;
The following code shows how to implement the final
keyword:
void main(){// declaring final variablefinal int num = 10;//calculating the sum and assign to variable sumint sum = num * num;// displaying resultprint(sum);}
Let’s try reassigning the value for variable num
in the following code:
void main(){// declaring final variablefinal int num = 10;//calculating the sum and assign to variable sumint sum = num * num;// displaying resultprint(sum);// reassigning variable numnum = 20;print(num);}
Note: If we try to reassign the variable
num
then it will display an error.