This Keyword
The this keyword is used to refer the current class object. It indicates the current instance of the class, methods, or constructor. It can be also used to call the current class methods or constructors.
The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
It can be passed as an argument in the class method or constructors.
- Example Of Using this:
- Syntactic Sugar
- Redirecting constructors
- Constant constructors
The Dart compiler might get confused if there are a number of the same name parameters. The result is the compiler will create ambiguity.
Without This :
class Person {
String name;
int id;
Person(name, id) {
name = name;
id = id;
}
}
void main() {
var p1 = Person("tom", 464385190);
print(p1.name);
print(p1.id);
}
null
With This :
class Person {
String name;
int id;
Person(name, id) {
this.name = name;
this.id = id;
}
}
void main() {
var p1 = Person("tom", 464385190);
print(p1.name);
print(p1.id);
}
464385190
That's why we use the this keyword to refer the current class object.
The pattern of assigning a constructor argument to an instance variable is so common, Dart has syntactic sugar to make it easy:
Example:
class Person {
String name;
int id;
Person(this.name, this.id);
}
void main() {
var p1 = Person("tom", 464385190);
print(p1.name);
print(p1.id);
}
464385190
Sometimes a constructor’s only purpose is to redirect to another constructor in the same class. A redirecting constructor’s body is empty, with the constructor call appearing after a colon (:).
Example:
class Vector3d {
int x, y, z;
void printCoordinates() {
print("x = $x y = $y z = $z");
}
Vector3d(this.x, this.y, this.z);
Vector3d.same(int s) : this(s, s, s);
}
void main() {
var v1 = Vector3d(1, 2, 3);
v1.printCoordinates();
var v2 = Vector3d.same(5);
v2.printCoordinates();
}
x = 5 y = 5 z = 5
If your class produces objects that never change, you can make these objects compile-time constants.
To do this, define a const constructor and make sure that all instance variables are final .
Const constructors can't have a body.
class Person {
final String name;
final int id;
const Person(this.name, this.id);
}
void main() {
var p1 = Person("tom", 464385190);
print(p1.name);
print(p1.id);
}
464385190