Static in Dart

Static In Dart

It generally manages the memory for the global data variable. Static variables are the same for every instance of the class. Using the class name, you can also call the static method and variables from other classes using the class name.

Info

Note: The static keyword is used to declare the class variable and method as static.

Dart Static Variable

All the variables declared using the static keyword inside the class are static variables. These are the member of the class instead of a specific instance. The static variables are treated the same for all instances of the class; it means a single copy of the static variable is shared among all instances of classes.

Syntax

class ClassName {
  static dataType variableName;
}

Example

class Student {
  static String studentName = "Suraj Subedi";
  static int rollNo = 213;
  static String address = "Pokhara";
}

void main(List<String> args) {
  print("Name of the student: ${Student.studentName}");
  print("Name of the student: ${Student.rollNo}");
  print("Name of the student: ${Student.address}");
}
Show Output

Dart Static Method

The static methods are the member of the class instead of the class instance. The static methods can use only static variables and can invoke the static method of the class. You don’t need to create an instance of the class to access it.

Syntax

class ClassName{
static returnType methodName(){
  //statements
}
}

Example

class Student {
  static String studentName = "Suraj Subedi";
  static int rollNo = 213;
  static String address = "Pokhara";

  static void printStudentDetails() {
    print("Name of the Student: ${Student.studentName}");
    print("Roll No: ${Student.rollNo}");
    print("Address: ${Student.address}");
  }
}

void main(List<String> args) {
  Student.printStudentDetails();
}
Show Output

Here, you can see that no object needs to be created to access the static method. Also, the static variable is directly accessible with the class name only.