Dart Factory Constructors
Dart Factory Constructors
A normal constructor always creates a new object of its own class.
A factory constructor is more flexible, and it is marked with the factory keyword.
It works like a function that must return an object, and it can decide which object to return.
A factory constructor can:
- check or change the arguments before an object is created
- return an object that already exists, instead of a new one
- return an object of a subclass
- create an object from data, like a Map
A Simple Factory
This factory constructor cleans up the name before it calls the normal constructor:
Example
class Person {
final String name;
Person._(this.name);
factory Person(String name) {
var clean = name.trim();
if (clean.isEmpty) {
clean = 'Unknown';
}
return Person._(clean);
}
}
void main() {
print(Person(' Liam ').name);
print(Person('').name);
}
Try it Yourself »
Result:
Liam
Unknown
Example Explained
Person._()is a named constructor called_.- A name that starts with an underscore
_is private, which means it can only be used in the same file. - The factory
Person()has a body with normal code, and ends withreturn. - Outside of the file, the only way to create a
Personis through the factory, so every name is always cleaned.
Note: A factory constructor cannot use this, because no object exists yet when it starts.
It cannot use the this.x shorthand or an initializer list either.
Return a Cached Object
A factory constructor can return an object that was created before.
This is called caching, and it saves memory when the same object is needed many times.
In this example, the class keeps all the colors it has created in a Map:
Example
class Color {
final String name;
static final Map<String, Color> _cache = {};
Color._(this.name) {
print('Creating $name');
}
factory Color(String name) {
return _cache.putIfAbsent(name, () => Color._(name));
}
}
void main() {
var a = Color('red');
var b = Color('red');
var c = Color('blue');
print(identical(a, b));
print(identical(a, c));
}
Try it Yourself »
Result:
Creating red
Creating blue
true
false
The keyword static means that there is only one _cache, shared by the whole class, and not one for each object.
You will learn more about it in the Static chapter.
The method putIfAbsent() returns the color that is already in the Map, or creates a new one and adds it.
"Creating red" is printed only once, because the second Color('red') returns the same object.
Return a Subtype
A factory constructor can return an object of a subclass.
A subclass is a class that is based on another class, and it is created with the extends keyword.
You will learn about subclasses in the Inheritance chapter.
Here, the factory Animal.fromSound() decides which kind of animal to create:
Example
class Animal {
Animal();
factory Animal.fromSound(String sound) {
if (sound == 'woof') {
return Dog();
}
if (sound == 'meow') {
return Cat();
}
return Animal();
}
String describe() => 'An animal';
}
class Dog extends Animal {
@override
String describe() => 'A dog';
}
class Cat extends Animal {
@override
String describe() => 'A cat';
}
void main() {
print(Animal.fromSound('woof').describe());
print(Animal.fromSound('meow').describe());
print(Animal.fromSound('moo').describe());
}
Try it Yourself »
Result:
A dog
A cat
An animal
The code that calls Animal.fromSound() does not need to know about Dog or Cat.
As you can see, a factory constructor can also be a named constructor.
Create an Object From a Map
The most common use of a factory constructor is to create an object from a Map.
Data from the internet often comes as JSON, a text format that Dart turns into a Map with string keys.
By convention, this factory is called fromJson:
Example
class User {
final String name;
final int age;
User(this.name, this.age);
factory User.fromJson(Map<String, dynamic> json) {
return User(json['name'] as String, json['age'] as int);
}
@override
String toString() => 'User($name, $age)';
}
void main() {
var data = {'name': 'Emma', 'age': 28};
var user = User.fromJson(data);
print(user);
}
Try it Yourself »
Result:
User(Emma, 28)
The type dynamic means that the values in the Map can be of any type.
The as keyword tells Dart which type each value has.
A factory works well here, because it can read and check the Map before it creates the object.
You can use it with map() to turn a list of Maps into a list of objects:
Example
class User {
final String name;
final int age;
User(this.name, this.age);
factory User.fromJson(Map<String, dynamic> json) {
return User(json['name'] as String, json['age'] as int);
}
@override
String toString() => 'User($name, $age)';
}
void main() {
var data = [
{'name': 'Liam', 'age': 31},
{'name': 'Olivia', 'age': 24},
];
var users = data.map((item) => User.fromJson(item)).toList();
print(users);
}
Try it Yourself »
Result:
[User(Liam, 31), User(Olivia, 24)]
You will learn how to read real JSON text in the JSON chapter.