Dart this Keyword
Dart this Keyword
The Dart this keyword is a reference to the current instance of the class. It allows you to access or refer to the current class’s members (variables and methods) within its own scope.
The this keyword is especially useful in situations where there might be ambiguity between instance variables and local variables or when you want to differentiate between a class member and a method parameter that have the same name. It can be also used to call the current class methods or constructors.
Dart this keyword
Let’s see some examples of usage of the this keyword:
Accessing instance variables:
class Person {
String name;
Person(this.name);
void printName() {
print(this.name); // Accessing the instance variable ‘name’
}
}
Differentiating between instance variables and method parameters with the same name:
Pass current instance
We can use the this keyword to pass the current instance as an argument to another function or constructor:
class MyClass {
int value;
MyClass(this.value);
void doSomething() {
AnotherClass another = AnotherClass(this); // Passing the current instance to the constructor of AnotherClass
// …
}
}
class AnotherClass {
MyClass myClass;
AnotherClass(this.myClass);
}
Note that you don’t always have to use this keyword to access instance variables. If there is no ambiguity with local variables or method parameters, Dart automatically understands that you are referring to the instance variables when you use their names within the class’s scope. However, using this can make your code more explicit and easier to read.
—
Dart Tutorials
Dart tutorial on this website can be found at:
https://www.testingdocs.com/dart-tutorials-for-beginners/
More information on Dart: