Factory Constructor in Dart
Introduction to the Factory in Dart, how it works, and its benefits for creating and initializing objects effectively.
factory Constructor
What is factory in real world ? Its a place where something happens inside of it and a finished or polished product comes out.
The same concept is applied in programming. A factory constructor is a constructor that returns an instance of the class ( as product, if you compare with real life). Let’s deep dive into it.
Familiar with the topic? Play Quiz
What is factory constructor ?
A factory constructor is a constructor that returns an instance of the class. Here is an example of a factory constructor in Dart:
class Person {
String name;
int age;
factory Person(String name, int age) {
return Person.namedConstructor(name, age);
}
Person.namedConstructor(String name, int age) {
this.name = name;
this.age = age;
}
}
Note:
Use case of factory constructor
There are many use cases of factory constructors. However, the frequent one is while working with backends and apis.
When we make a request to the backend, we get a json response. There is a concepts of converting datas to class models modern day programming. We we take a look at that in the lesson Flutter and Backend Intergration.
What that means is we get the data from APIs and we need to convert them to class models. However, if there are any required fields in the class model, we can’t create the objects without passing that field. In this scenario, factory constructor comes to the rescue.
Let’s take a look at an Example:
class Person {
String name;
int age;
factory Person.fromJson(String name, int age) {
this.name = name;
this.age = age;
}
}
Let’s assume the json response from the backend is:
{
"name": "John",
"age": 25
}
If we try to create an object of the class Person without passing the name
and age
fields, we will get an error. This can be done making the method static
or using the factory constructor ( recommended ). We will learn about static
keyword in the lessons ahead. Now let’s make use of the factory constructor to create an object of the class Person
without passing the name
and age
fields:
/// Note that name, and age are parameters of the factory constructor, not the class constructor.
/// At this point, we would have the data that we got from the backend.
final data = {
"name": "John",
"age": 25
};
/// lets pass the arugments to the factory constructor.
final person = Person.fromJson(data["name"], data["age"]);
/// Now we have the object of the class Person.
print(person.name); /// John
print(person.age); /// 25
Output
John
25
I hope you understood the use case of the factory
constructor. Let’s move forward.