Static members in Dart are class-level variables and methods that belong to the class itself rather than instances of the class. They provide a way to share data and functionality across all instances of a class.
Static variables, also known as class variables, are shared among all instances of a class. They are declared using the static
keyword.
class Counter {
static int count = 0;
}
Static variables are accessed using the class name, not through an instance:
print(Counter.count); // Outputs: 0
Static methods are functions that belong to the class rather than instances. They can be called without creating an object of the class.
class MathOperations {
static int add(int a, int b) {
return a + b;
}
}
void main() {
print(MathOperations.add(5, 3)); // Outputs: 8
}
Static members have some limitations:
this
keyword.To deepen your understanding of Dart's object-oriented features, explore these related topics:
Static members are a powerful feature in Dart, enabling efficient sharing of data and functionality across class instances. By understanding their proper use and limitations, you can write more efficient and organized Dart code.