Home > Software design >  Dart: Object is giving output only once even when called multiple times
Dart: Object is giving output only once even when called multiple times

Time:05-07

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

CodePudding user response:

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");

CodePudding user response:

calling the constructor only when you create a new object. Like

var x1 = Test("Boy1");
var x2 = Test("Boy2");
  • Related