Dart 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. It eliminates the uncertainty between class attributes and the parameter names are the same. If we declare the class attributes same as the parameter name, that situation will create ambiguity in the program, then the this keyword can remove the ambiguity by prefixing the class attributes. It can be passed as an argument in the class method or constructors.
Let's understand the following example of how this keyword works.
Example - Without using this keyword
Mobile's model name is: iPhone 11 , and the manufacture year is: 2020
In the above program, we created a class called Mobile, which has two attributes modelname and man_year. Then, we created a constructor and passed parameters the same as the class attributes name.
In the constructor body, the class variables (attributes) on the left side are assigned by the constructor parameters with the same name. When we create the instance of a class, the constructor automatically called the constructor and printed the result.
The Dart compiler might get confused if there are a number of the same name parameters. The result is the compiler will create ambiguity. That's why we use the this keyword to refer the current class object.
Example - 2: Using this keyword
Mobile's model name is: IPhone 11, and the manufacture year is: 2020
The above example is the same as the previous program, but the only difference of this keyword.
We have used the this keyword to the different instance or class variable from the local variable.
Points to Remember
Local variables are defined in the methods, constructors, or blocks. It is created when we create a method or constructor, and it has scope only inside them. We cannot use a local variable outside the method, constructor, or block.
Class variable is also known as the static member variable, which is used to declare using the static keyword. It is declared in the class, but outside a constructor, method or a block. All instances share one copy of the class variable or we can say that class variables are common to all instances of that class.
Instance variable is also known as the non-static, variable which is used to declare without the static keyword. The instance variables are specific by an object. These variables can be accessed using the instance of that class.
Difference Between Class Variable and Instance Variable
The following are the difference between the class variable and instance variable