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 🙂 .
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
void main(){ // Acceptable. const a = 20 ; // Acceptable. const double b = 2.22 ; // Acceptable. const int c = 12 ; // Acceptable. const String f = 'Sky'; // Not Acceptable in Root Main Class. Show Error. // Members can't be declared to be both 'var' and 'const'. const var d = 'hello'; } class Go{ // Acceptable. static const b = 40; // NOT Acceptable Shows Error. // Only static fields can be declared as const. const c = 50 ; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
void main(){ // Acceptable. final a = 20 ; // Acceptable. final double b = 2.22 ; // Acceptable. final int c = 12 ; // Acceptable. final String f = 'Sky'; // Not Acceptable in Root Main Class. Show Error. // Members can't be declared to be both 'var' and 'const'. final var d = 'hello'; } class Go{ // Acceptable. final b = 40; // Acceptable final c = 50 ; } |