Factory constructor

Factory constructor

class Logger { 
   final String name; 
   bool mute = false; 

   // _cache is library-private, thanks to the _ in front of its name. 
   static final Map<String, Logger> _cache = 
      <String, Logger>{}; 

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

   Logger._internal(this.name); 
   
   void log(String msg) { 
      if (!mute) print(msg); 
   } 
}
  • Use the factory keyword when implementing a constructor that doesn’t always create a new instance of its class.
  • Factory constructor might return an instance from a cache, or it might return an instance of a subtype.
  • Invoke a factory constructor just like you would any other constructor.
Note:

Factory constructors have no access to this.

Related concepts

Factory constructor

Factory constructor — Structure map

Clickable & Draggable!

Factory constructor — Related pages: