What is difference between final,const,static


The tricky question asked in Flutter interview is that “what is the difference between const and final keywords in flutter”?

Final keyword Summary in Dart

  • Variable values can not be changed once assigned with value
  • Final keyword variables access compile time and run time initialization
  • Class level static final variables must be initialized then and there
  • Class level final variables can be initialized at same line or at constructor

Please follow below post for more details on Final keyword :

Static Keyword In Dart:

Static – In Dart “static”  member is available on the class itself instead of on instances of the class.

Final variables can be static or even non static final variables are accepted at class level, but if you want to make const variable as class level then it should mark with static.

Class DisplayProduct { 
   final var sortType = "asc";
   static final var PRODUCT_HEADER="Product";
   static const diplayCount = 10;
}

Const Keyword in Dart: More details are explained in this “Const keyword in Dart”

  • const keyword used to make a variable to store a value at compile time.
  • Class level const variables must be marked with static keyword
  • Object level const variables are not allowed
  • Const used to make object as immutable by using const keyword before constructor.
  • When Const keyword used with list then all objects must be define at compile time and this list is deeply immutable.

Please follow below post for more details with example code

Leave a Reply

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