Dart  final and const keyword

Dart final and const keyword

Dart supports the assignment of constant value to a variable. These are done by the use of the following keyword:

  1. final keyword

  2. const keyword

This both keyword are use to keep the value static in whole program means once assign the variable and value it can to be altered in whole program.

While there are no limitation of use this keyword in program , we can use as many time keyword to give static value in code which can not change during the execution.

  1. Final Keyword

  • The final keyword is used to keep the values of the variable and it cannot be altered in future, also we can not process any kind of the performance in the variable.

  • Syntax

      // Without datatype
      final variable_name;
    
      // With datatype
      final data_type  variable_name;
    

    We can declare the final keyword with data type or without data type , in this we can not face any error.

  •   void main() {
    
      // Assigning value to geek1
      // variable without datatype
      final name1 = "Hello";
    
      // Printing variable geek1
      print(name1);
    
      // Assigning value to geek2
      // variable with datatype
      final String name2= "Hello again";
    
      // Printing variable geek2
      print(name2);
      }
    

    In this first we declare name1 variable and store value of string and after that we declare another variable name2 and store another string value.

  • In first we did not declare any data type with final keyword , while in second we have declare string as a data type.

  • In both we have choose different type of the variable , but if we chose same variable than we can face error in this program due to we can not change value of variable which are declare in final keyword.

  1. Const Keyword

  • The Const keyword in Dart exactly same as like the final keyword. The only difference between final and const is that the const makes the variable constant from compile-time only.

      // Without datatype
      const variable_name;
    
      // With datatype
      const data_type  variable_name;
    
    • In simple term , The “const” keyword is used to declare variables that are compile-time constants.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!