Factory methods
on Sunday, 19th of July, 2020
Factory constructors return am instance of the class, but it doesn't necessarily create a new instance. Factory constructors might return an instance that already exists, or a sub-class.
Rules for factory constructors:
- Factory constructors do use the
returnkey word. - You cannot refer to 'this' within the factory constructor.
class Cat {
String name;
String color;
// factory constructor that returns a new instance
factory Cat.fromJson(Map json) {
return Cat(json['name'], json['color']);
}
}
- previous: Properties and methods