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 return key 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']);
    }
} 


Join thousands of Flutter developers.

Sign up for infrequent updates about Flutter and Dart.

You can get all this content and more in one place. Check out my new book Flutter in Action