Const & Final Keyword in Dart Explained
Understanding const & final keywords, their Sytax, the Implementation, and the Difference
Previously we have understood with example the Dart Variables. In this article, I have explained what are final, and const keywords in Dart, the syntax, when to use them, and the difference between them.
We know that we can assign the values to variables, and we can also change them.
var name = “Ali”; // variable name is Ali
print(“name”); // prints value of name that is Ali.
// changing the value of variable “name”.
name = “Ahmed”; // change the value of name from Ali to Ahmed
print(“name”); // value of name will be printed that will be Ahmed since we have changed it from Ali above.
“//” is called Comments.
I hope you have understood it till now. But what if you don’t want to change the value of a variable. There are many cases in programming when you don’t need to change the value, and value that you assign to a variable at first time, that remains unchanged throughout the program. In such cases const, and final keywords come into the picture.
Final & Const
In Dart, both final, and const keywords are immutable. Immutable means their values can’t be changed. To make variables const or final, just the keyword before the variable name if it isn’t type casted or before the its type if its type is mentioned. See Type Casting here.
Using final
final fullName = “Ali Ahmed”; // without type casting
final String FirstName = “Ali”; // with type casting
We know that the value of const and final can’t be changed.
fullName = “Khan”; // this is wrong because we have already assigned value to it.
Using const
const pi = 3.14; // without type annotation or type casting
const double percentage = 87.6; // with type casting.
Since the value of const can’t be change so,
percentage = 89.5; // this is wrong.
Final vs Const: The Difference
We know that both final and const are immutable, and their values can’t be changed. But it is important to understand the difference between them in order to write a professional code.
Final
Final keyword is set at only once, and it is initialized when it is accessed. It means when you create a final variable, and assign a value to it, and don’t use it in your program then it doesn’t occupy the memory in your computer.
Const
Const keyword is compile time const. It means that it is assigned a memory location when program is compiled even if you don’t use it. If you created a const variable, the memory location will be assigned to it during compile time whether you use it or not.
That’s all for this article. I hope you have understood the const and final keywords, their implementation, and the difference. Thank you for reading this article