简体   繁体   中英

Factory and named constructor for json mapping in dart

Consider this code

class Album {
  int userId;
  int id;
  String title;

  Album({this.userId, this.id, this.title});

  Album.fromJsonN(Map<String, dynamic> json) {
    this.userId = json['userId'];
    this.id = json['id'];
    this.title = json['title'];
  }
  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(userId: json['userId'], id: json['id'], title: json['title']);
  }
}

In most tutorials the explanation for why we use factory for json mapping method is: "we use the factory keyword when implementing a constructor that doesn't always create a new instance of its class".

in factory method in above code, doesn't it returning a new instance? if it does, so whats the reason for using factory here? and whats the difference between factory constructor and fromJsonN named constructor in this context?

A Dart class may have generative constructors or factory constructors. A generative constructor is a function that always returns a new instance of the class. Because of this, it does not utilize the return keyword.

A factory constructor has looser constraints than a generative constructor. The factory need only return an instance that is the same type as the class or that implements its methods (ie satisfies its interface). This could be a new instance of the class, but could also be an existing instance of the class or a new/existing instance of a subclass (which will necessarily have the same methods as the parent). A factory can use control flow to determine what object to return, and must utilize the return keyword. In order for a factory to return a new class instance, it must first call a generative constructor.

Please see also Understanding Factory constructor code example - Dart for a very detailed explanation.

So for your question: Yes it is returning a new Instance but i guess the speciality comes from the fact that you the factory constructor is capable of creating an object based on an incoming json map whereas the generative constructor is used to instantiate a new object from single attributes.

And for your last question: Both do the same, namely returning an instance of the class given a json map. The techincal difference is that one is a generative and one a factory constructor.

One of the use cases when to use factory constructor or named constructor. To initialise the final fields of the class you have to do it in initializer list or in the declaration when using named constructor. On the other hand using factory constructor You can initialise the final fields in the body of the constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM