Const Keyword in Flutter


  1. const keyword used to make a variable to store a value at compile time.
const var value="Hellow" ; //accepted as value is defined at compile time
 // const var count; // This will cause error as count should assigned value
//const var todayDate = DateTime.now() // This will throw error as value assigned at runtime.

2. Class level const variables must be marked with static keyword. Object level const variables are not allowed

Class Product {

  static const int displayCount = 10; // This will not throw error 
  // const int displayCount=10; // This will throw error as instance level const variables are not allowed

}

3. Const used to make object as immutable by using const keyword before constructor. As shown in below prod variable is Immutable and you can reinitialize it again, but Product p1 is not marked with const, so it can assign with new product.

Class Product {
    final String productName;
    final int productId;
    const Product(this.productName, this.productId);
}
void main () {
    
    const  prod= const Product("Laptop", 101); 
     // prod is immutable and will throw error when we reinitialize a const variable

    // prod= const Product("Mobile", 102);

    // Below statements are acceptable and p1 can be reinitialized..
    Product p1= const Product("Laptop", 101);
    p1= const Product("Mobile", 102);
}

4.When Const keyword used with list then all objects must be define at compile time and this list is deeply immutable. As shown in below productList must be populate with compile time object only.

Class Product {
    final String productName;
    final int productId;
    const Product(this.productName, this.productId);
}
void main () {
    
    const productList = const [Product("Laptop",101),Product("Mobile",102)];
  
}

Const keyword Summary:

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

Leave a Reply

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