0

I have a model class that is a combination of two classes.

class UserItem{
 Item item;
 User user;

 UserItem(Item item, User user){
    this.item = item;
    this.user = user;
 }
}

I am basically trying to create a variables that are an instances of other classes. Dart is complaining and says I have to either instantiate or declare the item variable as late. I declared it as late and it is okay now. But is this the right way to proceed?

dianesis
  • 179
  • 2
  • 15
  • try: `UserItem(this.item, this.user);` – h8moss Sep 25 '21 at 19:27
  • it works like that. But I have a named construction called UserItem.fromJson(parsedJson) { user = User.fromJson(parsedJson[0], parsedJson[1], parsedJson[2]); item = ...) – dianesis Sep 25 '21 at 19:40
  • 1
    make it into a factory constructor like so: `factory UserItem(Map json) {return UserItem(json['item'], json['user'])}` Factory constructors work like static methods in the sense that they have to return an instance of the Object. – h8moss Sep 25 '21 at 19:52
  • 1
    @dianesis You could use an initializer list, as explained in the linked question: `UserItem.fromJson(List parsedJson) : user = User.fromJson(parsedJson[0], ...), ...;`. – jamesdlin Sep 25 '21 at 20:27
  • I changed the question because I actually want to combine two instances into a model class. Sorry I didn't express myself correctly in the question. – dianesis Sep 26 '21 at 00:16
  • 1
    @dianesis Again, use an initializer list. Is there some reason why you think that won't work for you? – jamesdlin Sep 28 '21 at 00:19
  • No, no particular reason. I ended up doing adding late to the variable and it worked. I could do whatever is the best approach. This helps. – dianesis Sep 28 '21 at 13:31

0 Answers0