'Dart: Object is giving output only once even when called multiple times
Hi I am trying to print value of 'a' property of x object but I only get output once.
void main() {
var x = Test("Boy");
x;
x;
x;
x;
x;
x;
}
class Test {
Test(var b) {
this.a = b;
print(a);
}
var a;
}
Output:
Boy
Solution 1:[1]
In constructor you call print function
Test(var b) {
this.a = b;
print(a);
}
Therefore - print is called whenever the constructor called.
Here you calling instance (variable), not constructor
x;
x;
x;
x;
x;
x;
It is printed once because you call constructor only once
var x = Test("Boy");
So if you try calling constructor multiple times then it will print multiple times
var x = Test("Boy");
var y = Test("Boy");
var z = Test("Boy");
Solution 2:[2]
calling the constructor only when you create a new object. Like
var x1 = Test("Boy1");
var x2 = Test("Boy2");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kerim |
| Solution 2 | AwadhJY |
