Bidev
IntermediateDart Questions

What is a factory constructor in Dart and when would you use one?

Short Answer

A factory constructor can return an existing instance instead of always creating a new one, or return a subtype — useful for caching/singleton patterns and for fromJson constructors that might return different subclasses based on the data.

A normal constructor always creates a new instance of exactly its own class. A factory constructor is a static-like method that must return some instance of the type (or a subtype), giving you control over instantiation — you could return a cached instance, look one up from a pool, or decide which of several subclasses to instantiate based on input.

The most common real-world use is a fromJson factory on a class hierarchy: factory Shape.fromJson(json) => switch (json['type']) { 'circle' => Circle.fromJson(json), ... } — something a regular constructor can't do, since it could never return a different subclass instance.

Code Example

class Logger {
  static final Map<String, Logger> _cache = {};

  factory Logger(String name) {
    return _cache.putIfAbsent(name, () => Logger._internal(name));
  }

  Logger._internal(this.name);
  final String name;
}

Common Mistakes

  • ×Assuming factory constructors can access this like a normal constructor — they can't, since they might not even create a new instance.
  • ×Overusing the singleton-via-factory pattern for things that would be simpler and more testable as an injected dependency.