static
variablesstatic
variables in Dart refer to the variables that are declared inside a class using the static
keyword.
Instead of a specific instance, these are members of the class. For all instances of the class, static variables are regarded the same. This means that a single copy of the static variable is shared by all instances of the class. It only allocates memory once, when classes are loading, and then uses it throughout the program.
The following are the key points to know about static variables:
A class variable is also called a static variable.
A single copy of the static variable is shared by all of a class’s instances.
The class name can be used to access static variables. We don’t need to create an object from the class they belong to.
Static variables can be easily accessed in static methods.
//To declare a static variable
static [data_type] [variable_name];
// To access a static variable
ClassName.staticVariableName;
The following code shows how to implement the static
keyword.
class Student {String roll_no;String level;// Declaring a static variablestatic var department;// Function to print details of the studentdisplayDetails() {print("The student with roll number ${roll_no} is in level ${level}.");print("The student studies ${department}");}}void main() {Student st1 = Student();// Accessing the static variableStudent.department = "Computer Sci";// Assigning value to variables using the class objectst1.roll_no = '1238AS23';st1.level = '400l';// Invokeing the method displayDetailsst1.displayDetails();}
Lines 1 to 9: We create a class named Student
, which has attributes matric_no
and level
, a static variable department
, and a method displayDetails()
.
Lines 15 to 2: In the main drive, we use the class name Student
to access the static variable, and use the class object to access to access non-static variable.
Line 26: Finally, the method displayDetails()
is called 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, it can access a non-static attribute within a static function.
class Student {// Declaring the non-static variableString name;//Declaring the static methodstatic display() {print("The student name is ${name}") ;}}void main() {// Creating an object of the class StudentStudent st1 = Student();// Accessing the non-static variablest1.name = 'Maria';// Invoking the static methodStudent.display();}