What is the difference between static, const, and final in Dart?

Google created Dart, a cutting-edge object-oriented programming language renowned for its dependable performance and adaptability. Dart excels at creating web and mobile apps focusing on client-side and server-side development. This is because of its expressive syntax, a robust ecosystem of libraries, and the frameworks like Flutter. Dart is a versatile solution for various application development scenarios because of its optional static typing and Just-In-Time (JIT) compilation. The final, const, and static are the keywords used in Dart to declare variables and constants, but they have different functions and behave differently. Let’s see how these keywords differ from one another:

The final keyword

Variables with a constant value assigned to them are declared using the final keyword. A final variable can be initialized both at the time of declaration, and in the constructor of the class to which it belongs. The final variables can’t be reassigned values after their initial assignment. The runtime environment may impact their values because final variables are evaluated at runtime.

class DummyClass {
  final int num; // Declare a final variable

  DummyClass(this.num); // Constructor to initialize the final variable

  void printValue() {
    print('Value of num: $num');
  }
}

void main() {
  final myInstance1 = DummyClass(42);
  final myInstance2 = DummyClass(100);

  myInstance1.printValue(); // Output: Value of num: 42
  myInstance2.printValue(); // Output: Value of num: 100

  // Attempting to change the value of a final variable will result in an error.
  // myInstance1.num = 50; // Output: Error 
  
}

The const keyword

Compile-time constants are declared with the const keyword. This indicates that they are immutable (can’t change during runtime) and that their values must be known at compile-time. Constant values calculated at compile-time include texts, numbers, expressions, and class objects that can be created using the const keyword. Const variables are often used for efficiency and optimization, and evaluated at compile-time. Const variables cannot be reassigned because they are implicitly final.

class DummyData{
  final int variable;

  const DummyData(this.variable); // constructor
  
  @override
  String toString() {
    return 'DummyData Variable is: $variable';
  }
}// Dummy Class


void main() {

  const object1 = DummyData(5);
  print(object1); // Output: DummyData Variable is: 5

  // You can’t modify the values of a const object
  // object1.variable = 20;
  // print(object1); // Output: Error

  // object1 = DummyData(10); // This line causes the error


  const int num = 20;
  // num = 30; // Error: Can’t assign to const variable 'num'
  print('Value of number: $num'); // Output: Value of num: 20
}

Also Read:- Difference Between Stateless and Stateful Widget in Flutter

The static keyword

Declaring variables and methods at the class level uses the static keyword. Rather than class instances, these variables and methods belong to the class. The static variables and methods are accessible, and shared by all class instances without generating a class instance. Once a static variable is defined and assigned a value, that value can be changed or modified during the program’s execution. Static variables in Dart retain their value throughout the program’s lifetime, but their contents can be altered as needed, making them mutable.

class DummyClass {
  static int num = 30; // Declare a static variable
  int num2 = 10; // non static variable
  
  // static method
  static void printValue() {
    print('Value of num: $num');
  }

  // non static method
  void printHello(){
    print("hello world");
  }

}

void main() {
  DummyClass.printValue(); // Output: Value of num: 30
  // DummyClass.printHello(); // Output: Error
  

  // You can access non static attributes and methods via instance of a class.
  DummyClass instance = DummyClass();
  print(instance.num2); // Output: 10

  instance.printHello(); // Output: Hello, world
}

The static variables, by nature, are mutable. However, the static keyword is mostly used along with the const or final keyword i.e., static const var1 = 10. The variables become immutable in that regard because of the attached const keyword properties.

We can best summarize the differences between the constfinal and const keywords in the table below.

  • Keywords: Describes the Dart keywords being compared.
  • Initialization: Explains when and how these keywords are initialized or used in code.
  • Evaluation time: Indicates when these keywords are evaluated during program execution.
  • Mutability: Defines whether variables declared with these keywords can be changed after the initial assignment.
  • Associated with: Specifies the specific elements or entities in Dart programming that are affected or related to each keyword.

KeywordsInitializationEvaluation TimeMutabilityAssociated With

final
At declaration or in a constructor
Runtime

Immutable

Instances of a class

const
At declaration or with compile-time expressions
Compile-time

Immutable

Compile-time

static

At declaration

Runtime
Depends on its declarationClass itself (not instances)

Conclusion

In Dart programming, keywords like finalconst, and static play distinct roles. The final and const both ensure variable immutability, while const specifically creates compile-time constants. The static variable operates at the class level, shared across instances. These concepts are vital for efficient, predictable code in Dart, benefiting web and mobile app development with frameworks like Flutter. Mastery of these keywords empowers developers to build adaptable and high-performance applications.

Also Read:- Top 100 Flutter interview questions and answers in 2024

Leave a Comment

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