So I am writing a program for my reference about the usage of this keyword. I declared a class variable, let's say 'x=1', in a class "Example". I declared a method inside that class, "method1". Inside that method as well, I declared another variable with name 'x=5' again. My intention is, without using this keyword, the ouput should be 5, i.e., local variable value. But when I use this keyword, the output will be 1, because it refers to the class variable. The code looks like This.
class Example{
int x=1
;
void method1()
{
int x=5;
print(x);
print(this.x);
}
}
This was working correctly as I expected. The problem arises when I tried to combine the code with the $ operator.
So I rewrote the code in this way for better reference
class Example{
int x=1;
void method1()
{
int x=5;
print("I am $x");
print("I am $this.x");
}
}
This is where the problem arises. The first line of code prints the value correctly as "I am 5". But the next line, instead of printing "I am 1", prints something like this
"I am Instance of 'Example'.x"
I have no Idea what this means, I am new to Object Oriented Programming and dart. Is this throwing some exception? What the compiler is trying to say? Is this some wierd interaction between the this keyword and $ operator? And Most importantly, how to rectify it? Thanks in advance.
In Dart, to use string interpolation where the expression is not an identifier, use
${expression}.See: String interpolation