Difference Between Constant And Final Explained In Flutter

admin_img Posted By Bajarangi soft , Posted On 03-11-2020

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 🙂 .

Difference Between Constant And Final Explained In Flutter

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 ;
}



2.Final Explained: 
  - 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:

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 ;
}

Related Post