What is the this keyword in Dart ?
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
void main() {
Student s1 = new Student('S001');
}
class Student {
var st_id;
Student(var st_id) {
this.st_id = st_id;
print("THIS Example");
print("The Student ID is : $st_id");
}
}
Output
THIS Example The Student ID is : S001 Exited.