this is a keyword in Dart language and points to a current class object.

This is used in a method or constructor to refer to the class instance member variables and methods.

It helps to solve ambiguity for the same field names declared in local variables and global instance variables.

Syntax:

this.instancevariable
this.method()

Dart this keyword example

The example explains how to use this keyword in the constructor in a class In the constructor, this. id refers to a class instance variable.

class Employee {
  int id = 0;
  String name='';
  Employee(int id, String name) {
    this.id = id; // this keyword used
    this.name = name; // this keyword used
  }
}

void main() {
  Employee e1 = new Employee(1, "john");
  print(e1.id); // 1
  print(e1.name); // john
}

The same can be rewritten in a shorter way using Dart constructor this keyword.

In this class member, instance variables are initialized in the constructor itself.

class Employee {
  int id = 0;
  String name;
  Employee(this.id, this.name) {}
}

void main() {
  Employee e1 = new Employee(1, "john");
  print(e1.id); // 1
  print(e1.name); // john
}

Important points.

  • this keyword points to the current class object instance
  • Access the instance variables in the constructor and methods
  • Helps to avoid ambiguity with instance variables in a class and local variables in the constructor and method
  • uses to call and execute the methods of the same class
  • uses to pass these files as arguments in the constructor and a method