This keyword in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

This keyword in dart is used to remove the ambiguity that can be caused if the class attributes and the parameters have the same name. This keyword basically represents an implicit object pointing to the current class object.

We usually prefix the class attribute with this keyword whenever we want to remove the ambiguity between the class attributes and the parameters.

Example

Let's take two examples of the case where the name of the class attribute and the parameters are the same.

Consider the example shown below −

 Live Demo

void main() {
   Employee emp = new Employee('001');
   emp.empCode = '111';
}

class Employee {
   String empCode;
   Employee(String empCode) {
      this.empCode = empCode;
      print("The Employee Code is : ${empCode}");
   }
}

In the above code, we can clearly see that the class Employee has an attribute named empCode and also a parameter with the same name. So, later in the Employee() constructor, we simply use this keyword to remove the ambiguity caused by the same name.

Output

The Employee Code is : 001

Example

Let's consider another example with a different class and attribute.

Consider the example shown below −

 Live Demo

void main() {
   Student studentOne = new Student('001');
   studentOne.studentId = '99';
}

class Student {
   // local studentId variable
   var studentId;
   Student(var studentId) {
      // using this keyword
      this.studentId = studentId;
      print("The Student ID is : ${studentId}");
   }
}

Output

The Student ID is : 001
raja
Published on 24-May-2021 12:13:05
Advertisements