Skip to main content

Command Palette

Search for a command to run...

Dart: Static variable & static method

Updated
2 min read
Dart: Static variable & static method

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.

Dart

Part 37 of 50

I'll be here to provide explanations, examples, and assistance as you explore the depths of Dart programming language. Together, we'll unravel the intricacies of Dart, from its fundamental concepts to

Up next

Dart Inheritance: Prefer Composition over Inheritance

While inheritance is a powerful concept, it's often recommended to favor composition over inheritance to achieve more flexible and maintainable code. Composition involves building classes by combining simpler classes rather than inheriting from them....

More from this blog

Flutter Journey with Jinali

141 posts