Dart: Static variable & static method

Jinali GhoghariJinali Ghoghari
2 min read

Static variable or class variable & static method is based on the class.

Static variable:

void main() {
    var obj = A();
    print(A.y);
}

class A
     //int x = 10;
    static int y = 20;
} 
// output: 20
  • The class name is required to access the static variable.

  • So, this static variable is created only once in the entire class.

Static Method:

  • Static methods (class methods) don't operate on an instance, and thus don't have access to this.

  • They do however have access to static variables.

  • An static method is related to a class rather than an object of the class. We can call the static method directly without creating an object of the class.

  • Static methods are designed in such a way that they can be shared among all objects created using the same class.

void main() {
    //var obj = A();
    A.display();// Static Method call
}

class A
    int x = 10;
    static int y = 20;

    static void display() {
    print(y);
    }
} 
// output: 20
  • Within a static method, we can only access static variables.

    Benefits of Static Variables and Methods:

    1. Memory Efficiency: Static variables consume memory only once, regardless of the number of instances created, making them memory-efficient.

    2. Shared Data: Static variables allow sharing of data among all instances of the class, enabling centralized management of common resources.

    3. Utility Functions: Static methods provide a convenient way to define utility functions that are not tied to any particular instance, enhancing code organization and readability.

0
Subscribe to my newsletter

Read articles from Jinali Ghoghari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jinali Ghoghari
Jinali Ghoghari