What is the this keyword in Dart programming?

The this keyword is used to refer to the current class instance. this can be used to invoke the current class’s constructors or methods. It also helps access the current class’s instance variables.

The this keyword can be used to set the instance variable’s values or get the current instance of the class.

Why use the this keyword?

Suppose the declared class attributes are the same as the parameter name, and the program becomes ambiguous. We can eliminate this ambiguity by prefixing the class attributes with the this keyword.

The this keyword can be given as an argument to the constructors or methods of the class.

Example

The example below demonstrates how to use the this keyword to call an instance variable.

// Creating class Student
class Student {
// Creating instance variables
String matric_no;
int course;
// Creating a parameterized constructor
Student(String matricNo, int course_info){
// Calling instance variables using this keyword.
this.matric_no = matricNo;
this.course = course_info;
}
// Class method
void display_info(){
print("Student $matric_no is offerring $course courses this semester");
}
}
void main(){
// Creating instance of the class Student
// and assigning values
Student s1 = new Student("186HQ025", 10);
// Calling method
s1.display_info();
}

Free Resources