Dart : Static variable & static method

Dart : Static variable & static method

·

1 min read

Static variable :

  • static variable in Dart refer to the variable that are declared inside a class
    using the static keyword.

  • Instead of a specific instance, these are members of the class.

  • For all instances of the class, static variables are regarded the same.

  • This means that a single copy of the static variable is shared by all instances of

    the class.

  • A class variable is also called a static variable.

  • A single copy of the static variable is shared by all of a class’s instances.

Static Method :

  • static methods are members of the class rather than the class instance in Dart.

  • static methods can only use static variables and call the class's static
    method.

  • To access the static method, we don't need to create a class instance.

  • To make a method static in a class, we use the static keyword.

  • Instead of the object, the static methods are the member class.

Example :

  •   class MyClass {
          static int staticVar = 10;
    
          static void printStaticalVar() {
              print(staticVar);
          }
    
          int count = 0;
    
          void increment() {
              count++;
          }
      }
    
      void main() {
          print(MyClass.staticVar);
          MyClass.printStaticVar();
    
          var counter1 = MyClass();
          counter1.increment();
          print(counter1.count);
    
          var counter2 = MyClass();
          counter2.increment();
          print(counter2.count);
    
      }
    
  •   10
      10
      1
      1
    
      Exited.