![]() |
VOOZH | about |
Dart supports the assignment of constant value to a variable. These are done by the use of the following keywords:
These keywords are used to keep the value of a variable static throughout the code base, meaning once the variable is defined its state cannot be altered. There are no limitations if these keywords have a defined data type or not.
The final keyword is used to hardcode the values of the variable, and it cannot be altered in the future; neither can any kind of operations performed on these variables alter its value (state).
// Without datatype
final variable_name;
// With datatype
final data_type variable_name;
Example :
Output:
Geeks For Geeks
Geeks For Geeks Again!!
Note : If we do not assign a value to a final variable and tries to use it, reassigning it will result in an error as below.
Error 1 : Using an uninitialized
finalvariableError: Final variable 'geek1' must be assigned before it can be used.
print(geek1);
Error 2 : Attempting to reassign afinalvariableCan't assign to the final variable 'geek1'.
geek1 = "Geeks For Geeks Again!!";
The Const keyword in Dart behaves similarly to the final keyword. The only difference between final and const is that the const makes the variable constant from compile-time only. Using const on an object makes the object's entire deep state strictly fixed at compile-time, and the object with this state will be considered frozen and completely immutable.
Example :
Output:
Geeks For Geeks
Geeks For Geeks Again!!
Without Const Keyword
Output :
false
[1, 2]
[1, 2]
With Const Keyword
Output :
true
[1, 2]
[1, 2]
Note : If we do not assign a value to a const variable and tries to use it or not , reassigning it will result in an error as below.
Error 1 : Using an Uninitialized
constVariableError: The const variable 'geek1' must be initialized.
Try adding an initializer ('= expression') to the declaration.
const geek1 ;Error 2 : Attempting to Reassign a
constVariableError: Can't assign to the const variable 'geek1'.
geek1 = "Geeks For Geeks Again!!";