thumbnail

Factory Constructor In Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Use of Factory Keyword

Factory keyword is used when implementing constructors that do not create new instances of the existing class.

A factory constructor can return value from cache or from an instance of a sub-type.

Factory constructor does not have access to this keyword.

Factory constructors are like static methods whose return type is the class itself.

Proper use case of factory constructor:

  • Use factory constructor when creating a new instance of an existing class is too expensive.
  • Creating only one instance of the class.
  • For returning sub-class instance of the class instead of the class itself.
// program to demonstrate use of Factory constructor

class Shape {
  // type of the shape being created
  final String type;

  // id of this shape for identifying what instance is it
  final int id;

  // library private variable because of _ being used
  static final Map<String, Shape> _cache = <String, Shape>{};

  // factory constructor
  factory Shape(String type, {int id}) {
    // puts new object in cache or returns existing object that is already stored in cache
    return _cache.putIfAbsent(
        type,
        () => Shape._init(
              type,
              id,
            ));
  }

  // initialize new shape
  Shape._init(this.type, this.id);

  // prints information about current shape
  void printInfo() {
    print('shape type is: ${type}, shape id is: ${id}');
  }
}

main(List<String> args) {
  // initializing a circle
  new Shape('circle', id: 2)..printInfo();
  // no shape id is specified
  new Shape('circle')..printInfo();
}

Above program produces following output:

shape type is: circle, shape id is: 2
shape type is: circle, shape id is: 2

Explanation of above program: Above program makes use of factory constructor to initialize a new variable or to return an object that is already initialized from cache.

We hope that you have found this guide useful for learning factory constructors in Dart.