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
staticmethods are the member class. staticmethods are also known as class methods.- The class name is used to access static methods.
- A single copy of a
staticmethod 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 methodclass Car {// declaring static variablestatic String name;//declaring static methodstatic display() {print("The car name is ${Car.name}") ;}}void main() {// accessing static variableCar.name = 'Toyota';// invoking the static methodCar.display();}
Note:
staticmethods can only usestaticvariables.
Explanation
-
Lines 3 to 10: We create a class named
Car, which has the attributenameof thestatictype and astaticmethoddisplay(). -
Lines 13: In the main drive, we use the class name
Carto 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
erroris 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 variableString name;//Declaring the static methodstatic display() {print("Car name is ${name}") ;}}void main() {// Creating an object of the class CarCar car = Car();// Accessing the non-static variablecar.name = 'Toyota';// Invoking the static methodCar.display();}