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:
static
methods are the member class.static
methods are also known as class methods.static
method is spread across all instances of a class.// declaring a static method
static return_type method_name() {
//statement(s)
}
// invoking a static method
className.staticMethod();
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:
static
methods can only usestatic
variables.
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 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();}