Skip to main content

Command Palette

Search for a command to run...

Dart Defined Constant using final and const keyword

Published
1 min readView as Markdown
P

I'm Computer Engineering Student. Learning Status DSA in Java, Dart Development, Python in Django Development. Best part is Communication Skills, Marketing, Accounting.

In Dart, both final and const are used for defining constants, but they behave differently:

  1. final:

    • final variables can only be set once and cannot be changed afterwards.

    • They are initialized the first time they are used.

    • Their value can be determined at runtime.

    • They are not implicitly const and can hold values computed at runtime.

    • Example:

        final int x = 10;
        final String name = "John";
      
  2. const:

    • const variables are implicitly final but are compile-time constants.

    • They must be initialized with a constant value, known at compile-time.

    • They are eagerly initialized at compile-time.

    • They can hold literals and constant expressions, but not variables.

    • Example:

        const int y = 20;
        const double pi = 3.14;
      

Example illustrating the difference:

final int a = 10;
const int b = 20;

void main() {
  final int c = a + 5; // Valid, a is a runtime constant
  // const int d = b + 5; // Invalid, b is a compile-time constant, but expression involves runtime calculation
}

In summary, use final when the value of the variable might change at runtime but is set only once, and use const when the value is known at compile-time and will never change.

More from this blog

Parth Chauhan's blog

87 posts

Learner, Accountant, Marketer, Programmer.