Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dart advantage of a factory constructor identifier

Tags:

flutter

dart

I've been investigating JSON parsing for my Flutter app and have a question about factory constructors that I can't resolve. I'm trying to understand the advantage of using a factory constructor versus a plain constructor. For example, I see quite a few JSON parsing examples that create a model class with a JSON constructor like this:

class Student{   String studentId;   String studentName;   int studentScores;    Student({     this.studentId,     this.studentName,     this.studentScores   });    factory Student.fromJson(Map<String, dynamic> parsedJson){     return Student(       studentId: parsedJson['id'],       studentName : parsedJson['name'],       studentScores : parsedJson ['score']     );   } } 

I've also seen an equal number of examples that DON'T declare the constructor as a factory. Both types of classname.fromJSON constructors create an object from the JSON data so is there an advantage to declaring the constructor as a factory or is using a factory here superfluous?

like image 223
mjordan Avatar asked Sep 12 '18 16:09

mjordan


People also ask

What is the advantage of factory constructor in Dart?

A factory constructor is a constructor that can be used when you don't necessarily want a constructor to create a new instance of your class. This might be useful if you hold instances of your class in memory and don't want to create a new one each time (or if the operation of creating an instance is costly).

What is a factory constructor Dart?

Overview. In Dart, we use the factory keyword to identify a default or named constructor. We use the factory keyword to implement constructors that do not produce new instances of an existing class.

What is the use of constructor in Dart?

A constructor is a special function of the class that is responsible for initializing the variables of the class. Dart defines a constructor with the same name as that of the class. A constructor is a function and hence can be parameterized. However, unlike a function, constructors cannot have a return type.

Why do we use factory in flutter?

Factory Method is referred as a creational design pattern which provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. Also known as virtual constructors. Lets clear it with a small code.


2 Answers

A normal constructor always returns a new instance of the current class (except when the constructor throws an exception).

A factory constructor is quite similar to a static method with the differences that it

  • can only return an instance of the current class or one of its subclasses
  • can be invoked with new but that is now less relevant since new became optional.
  • has no initializer list (no : super())

So a factory constructor can be used

  • to create instances of subclasses (for example depending on the passed parameter
  • to return a cached instance instead of a new one
  • to prepare calculated values to forward them as parameters to a normal constructor so that final fields can be initialized with them. This is often used to work around limitations of what can be done in an initializer list of a normal constructor (like error handling).

In your example this code

  studentId: parsedJson['id'],   studentName : parsedJson['name'],   studentScores : parsedJson ['score'] 

could be moved to the body of a normal constructor because no final fields need to be initialized.

like image 152
Günter Zöchbauer Avatar answered Sep 19 '22 17:09

Günter Zöchbauer


In the particular example in the question, there's no advantage to using a factory constructor. It makes no difference to callers (there is no expectation to receive an already-existing object), and this particular factory constructor could have been a normal constructor that delegated to the main constructor instead.

In general, the factory keyword is not very useful and provides an advantage only in special circumstances.


A factory constructor vs. a normal constructor

  • A factory constructor invokes another constructor.
  • Since a factory constructor does not directly create a new instance, it cannot use a constructor initializer list.
  • A normal constructor always returns a new instance of the class. A factory constructor is permitted to return an existing instance, an instance of a derived class, or null. (However, some people dislike returning null from a factory constructor. Note that returning null from a factory constructor is disallowed with null-safety.)
  • Due to the above, an extending class cannot invoke a factory constructor as the superclass constructor. A class that provides only factory constructors therefore cannot be extended with derived classes.

A factory constructor vs. a static method

  • A factory constructor can be the unnamed, default constructor of a class.
  • A factory constructor can be used with new. (But using new is now discouraged.)
  • Until Dart 2.15, constructors could not be used as tear-offs (i.e., they can be used as callbacks), whereas static methods could.
  • Static methods can be async. (A factory constructor must return a type of its class, so it cannot return a Future.)
  • Factory constructors can be declared const.
  • In null-safe Dart, a factory constructor cannot return a nullable type.
  • In generated dartdoc documentation, a factory constructor obviously will be listed in the "Constructors" section (which is prominently at the top) whereas a static method will be in the "Static Methods" section (which currently is buried at the bottom).
like image 39
jamesdlin Avatar answered Sep 20 '22 17:09

jamesdlin