What are static methods in Dart?

The Dart 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.

The following are the critical points to note about the static method:

  • Instead of the object, the static methods are the member class.
  • static methods are also known as class methods.
  • The class name is used to access static methods.
  • A single copy of a static method is spread across all instances of a class.

Syntax

// declaring a static method
static return_type method_name() {  
 //statement(s)  
}  
// invoking a static method
className.staticMethod();  

Code

The following code shows how to implement the static method:

// Dart program to illustrate static method
class Car {
// declaring static variable
static String name;
//declaring static method
static display() {
print("The car name is ${Car.name}") ;
}
}
void main() {
// accessing static variable
Car.name = 'Toyota';
// invoking the static method
Car.display();
}

Note: static methods can only use static variables.

Explanation

  • Lines 3 to 10: We create a class named Car, which has the attribute name of the static type and a static method display().

  • Lines 13: In the main drive, we use the class name Car to access the static variable.

  • Line 16: Finally, the displayDetails() method is called using the class name to display the result.

Note: When a non-static attribute is accessed within a static function, an error is thrown. This is because a static method can only access the class’s static variables.

For example, let’s try accessing a non-static attribute within a static function:

class Car {
// Declaring the non-static variable
String name;
//Declaring the static method
static display() {
print("Car name is ${name}") ;
}
}
void main() {
// Creating an object of the class Car
Car car = Car();
// Accessing the non-static variable
car.name = 'Toyota';
// Invoking the static method
Car.display();
}

Free Resources