In Dart, factory constructors needs more logic from coders, but not so different from const ones except they permit \'Non final\' instance variables.
What are their
A factory constructor and a const constructor fulfill entirely different purposes. A const constructor allows to have an instance of a custom class in a compile time constant expression. See https://stackoverflow.com/a/21746692/217408 for more details about the const constructor.
A factory constructor and a constant method that returns a new instance of a class are more similar. The difference is, that a factory constructor is called with new
like a normal constructor and has some limitations a constant method doesn't have.
The main difference between a normal constructor and a factory constructor is, that you can influence if actually a new instance is created and of what concrete type it is.
In https://www.dartlang.org/dart-tips/dart-tips-ep-11.html a cache is mentioned as a popular example. A factory constructor can check if it has a prepared reusable instance in an internal cache and return this instance or otherwise create a new one.
Another example is the singleton pattern. See https://stackoverflow.com/a/12649574/217408 for more details.
Another example is the factory pattern.
You can for example have an abstract class A
(which can't be instantiated) with a factory constructor that returns an instance of a concrete subclass of A
depending for example on the arguments passed to the factory constructor.
Here is a similar question Dart - Trying to understand the value of 'factory' constructor