Difference Between Constant And Final Explained
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.
- Even if we do not use Constant variable in our program it will assign memory to them.
- When program starts compiling it will allocate memory to const variables.
- 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:
void main(){
// Acceptable.
const a = 22;
const double b = 3.22 ;
const int c = 11;
const String f = 'Sky';
// Not Acceptable in Root Main Class. Show Error.
const var d = 'hello world';
}
class Go{
// Acceptable.
static const b = 40;
// NOT Acceptable Shows Error.
// Only static fields can be declared as const.
const c = 50 ;
}
void main(){
// Acceptable.
final a = 22;
// Acceptable.
final double b = 3.22 ;
// Acceptable.
final int c = 11;
// 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 world';
}
class Go{
// Acceptable.
final b = 40;
// Acceptable
final c = 50 ;
}