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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Jul 17, 2012, 4:38 AM
http://www.dartexperience.com/en/tag/ejemplos/
Satyapriya NayakPosted Jul 17, 2012, 4:36 AM
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.
void main() { Config c = new Config(); c.x =10; c = new Config(); print(c.x); }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