0

So there is 2 classes where I would like to pass class Two as param to One's constructor. But dart complains that I did not initiate pro1 and prop2

class Two {
 int propA = 1;
 int propB = 2;
 int propC = 3;
}

class One {
  One(Two two){
     prop1 = two.propA + two.propB;
     prop2 = two.propC + 3;
}
  int prop1;
  int prop2;
}

ViniciusCR
  • 83
  • 1
  • 7

1 Answers1

1

Like this:

class Two {
  int propA = 1;
  int propB = 2;
  int propC = 3;
}

class One {
  One(Two two)
      : prop1 = two.propA + two.propB,
        prop2 = two.propC + 3;
  int prop1;
  int prop2;
}

Class instance variables needs to be defined as part of initializing the object which happens before running the constructor body. To add logic to the initialization, we do that by inserting code after a : (and before an eventually {).

julemand101
  • 28,470
  • 5
  • 52
  • 48
  • great! that worked! It is quite tricky. I think I saw that before but did not understand. Is it possible to add any extra code there, like declare a temporary variable or I must only assign values to props? – ViniciusCR Aug 30 '22 at 17:25
  • It is limited what logic you can have as part of the initialization of an object. But a trick you can use is declare a factory constructor that does complicated logic and then returns an instance of your class using a "dumb" constructor that just takes the values and puts them into the object. – julemand101 Aug 30 '22 at 17:29
  • I though about it, but I wouldn't end up with all prop been optimal or a constructor with lots of params that would be public but never used? – ViniciusCR Aug 30 '22 at 17:37
  • Well, you can make the constructor private and then have only the factory constructor as the public way to "construct" an object. – julemand101 Aug 30 '22 at 17:37
  • True true, some design pattern to be applied here. It has been a while since I have suffered from OOP's problems, almost forgot all about it. I miss functional programming already. – ViniciusCR Aug 30 '22 at 21:30