Static Keyword
- Static Keyword
- Static Variable
- Static Methods
- Example :
In Dart, a static member is a member of a class that isn’t associated with an instance of a class.
Instead, the member belongs to the class itself. As a result, you can access the static member without first creating a class instance.
The static members are the same for every instance of the class.
We can call the static variable as a class variable.
The value of a static variable is the same across all instances of the class. In other words, if a class has a static field named x, all objects created from the class will have the same value for x.
We can access to it using the class name so there are no need for creating an object to do that.
Declaring Static Variable :
Accessing Static Variable :
A method declared with the static keyword. Like static variable, static methods are associated with the class itself, not with any particular object created from the class. As a result, you don’t have to create an object from a class before you can use static methods defined by the class.
One of the basic rules of working with static methods is : you can’t access a nonstatic method or variable from a static method.
Declaring Static Methods :
//method body
}
Calling Static Method :
class Person {
String name;
int id;
static int nbOfPerons = 0;
Person(this.name, this.id) {
nbOfPerons++;
}
static void printNbOfPersons() {
print(nbOfPerons);
}
static void modifyNbOfPerons(int x) {
nbOfPerons = x;
}
void printNbOfPersonsFromObject() {
print(nbOfPerons);
}
}
void main() {
Person.printNbOfPersons();
var p1 = Person("Adem", 12345);
var p2 = Person("John", 65437);
var p3 = Person("Tom", 97072);
Person.printNbOfPersons();
Person.modifyNbOfPerons(8);
Person.printNbOfPersons();
Person.nbOfPerons = 15;
Person.printNbOfPersons();
p1.printNbOfPersonsFromObject();
p2.printNbOfPersonsFromObject();
p3.printNbOfPersonsFromObject();
}
3
8
15
15
15
15