Flutter Dart Difference Between Constant and Final Explained Example

In Dart programming language we have heard about two most used keywords Const and Final. In Today’s tutorial we would learn about what are major difference between Constant and Final keyword in dart in fully explained example. We would also learn about how to declare constant and final variables in dart programming language. So let’s get stated 🙂 .

Flutter Dart Difference Between Constant and Final Explained Example

1. Constant :- 

Constant variables are declared with const keyword in dart. Constant variables are by default final variables in nature in dart. In dart all the constant are compiled time constant means all the constant variables will automatically initialized memory on program compile time. When program starts compiling it will allocate memory to const variables. Even if we do not use Constant variable in our program it will assign memory to them. Another major difference is if we want to declare a class level constant then we have to make it in Static also in dart. We can directly used Const in main class but in other class we have to define static const. In below example i have mentioned comment above each constant variable declaration with Acceptable and Not Acceptable. Using this you would know which syntax is correct and which is wrong.

Example:

2. Final :-

Final variables assign with final keyword in dart. Final variables cannot change once initialize in program. It will be fixed always. The main difference between final and constant are final variables can only be initialized memory when they are used in program. If we define final variable and dose not use them then it will not consume memory.

Example:


 

Leave a Reply

Your email address will not be published. Required fields are marked *