Dart static Keyword

In this tutorial you will learn about the Dart static Keyword and its application with practical example.

Dart static Keyword

The static keyword is used for memory management of global data members. The static keyword can be applied to the fields and methods of a class. The static variables and methods are part of the class instead of a specific instance. The static keyword is used for a class level variable and method that is the same for every instance of a class; this means if you make a data member static, you can access it without creating a object. The static keyword allows data members to persist values between different instances of a class. There is no need to create a class object to access a static variable or call a static method; simply put the class name before the static variable or method name to use them.

Dart Static Variables

The static variables belongs to the class instead of a specific instance. A static variable is common to all instances of a class; this means only a single copy of static variable is shared among all the instances of a class. The memory allocation for static variable happens only once in class area at the time of class loading.

Important Points :-

  • Static variables are also known as Class Variables.
  • Static variables can be accessed directly in Static method
  • Single copy of static variable is shared among all the instances of a class

Declaring Static Variables

Static variables can be declared using the static keyword followed by data type then variable name.

Syntax:-

Accessing Static Variable

Static variable can be accessed directly from the class name itself rather than creating an instance of it.

Syntax:-

Dart Static Methods

Same as static variable, static method belong to class instead of class instances. A static method is only allowed to access the static variables of class and can invoke only static methods of the class. Usually, utility methods are created as static methods when we want it to be used by other classes without the need of creating an instance.

Important Points :-

  • Static methods are also known as Class Methods.
  • Static method is only allowed to access the static variables of class.
  • Single copy of static method is shared among all the instances of a class
  • Static methods can be accessed directly using class name.

Declaring Static Methods

Static method can be declared using static keyword followed by return type, followed by method name.

Syntax:-

Calling Static Method

Static methods can be invoked directly from the class name itself rather than creating an instance of it.

Syntax:-

Example:-

Output:-

dart_static_keyword_example

In this tutorial we have learn about the Dart static Keyword and its application with practical example. I hope you will like this tutorial.