Factory constructor in Dart
how to create a factory constructor in dart.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Satyapriya NayakRank #47 · 31.5K reputationPosted Jul 17, 2012, 12:36 AM EDT
Factory Constructor:- This constructor does not create a new instance of the class but returns an instance based on logic like Singleton or from a cache.
The code below shows a Singleton implementation. The _internal is basically like a private constructor used from the factory constructor to internally create an instance.
class Config { static Config cfg ; int x; factory Config(){ if(cfg==null) { cfg = new Config._internal(); } return cfg; } Config._internal(){} }The snippet shown below will print 10 proving that factory constructor is returning the same instance every time it is invoked.
There is another type of constructor called Constant Constructors used to create compile time constant or immutable object using const keyword as shown below:
class Test{ final int x,y; const Test (this.x,this.y); }Constant object with identical properties are basically the same object instance. So the code below will print true.
void main() { var a = const Test(10,20); var b = const Test(10,20); print(a==b); }Please refer the below link
http://codingndesign.com/blog/?p=278
Thanks
VulpesRank #55 · 29.2K reputationPosted Jul 17, 2012, 12:38 AM EDT
http://www.dartexperience.com/en/tag/ejemplos/