We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

Chris Sells • 5 years ago

Factory constructors can't be async; static methods can be.

J. Courtland Colburn • 3 years ago

While I do mostly agree with you (as I have also wanted async constructors) I feel like having an object that isn't yet itself would make it's 'this' into 'thisButNotJustYet'.

Luk • 5 years ago

Regarding readability, static methods can take advantage of tear off, while factory constructors can't (yet).


bar(Foo.fromJson); // fromJson as static method
bar((payload) => Foo.fromJson(payload)); // fromJson as factory constructor

J. Courtland Colburn • 3 years ago

Guess who's here ...tear offs made it to the party! https://uploads.disquscdn.c...

Mateus Felipe C. C. Pinto • 5 years ago

This is the main reason I use only `static` over `factory`. The cases pointed in this article are all irrelevant to be, but I often use the pattern, so `fromJson` is always `static` in my codes.

Frank Moreno Vera • 5 years ago

That is because a constructor is not a method.

Sergey Molchanovsky • 3 years ago

The most important difference is not mentioned here.
Factories can return a subtype (factory in Animal class can return a Cat instance), but static methods can't.

Jongyon Lee • 5 years ago

Wow.. the article and replies are very helpful. Thank you very much!

Richard Shepherd • 2 years ago

Been asking myself this lately - and came across this article & discussion - very interesting all the concise-ness stuff - thx Remi.

I use factory constructors to process API-response data and do all the extraction/transformation work to produce a new (or cached or const) instance of my model-classes. However, with null-safety, factory constructors now always have to return a valid instance - even if the data is invalid - and so they seem a bit less useful...

A static pseudo-constructor, OTOH, can be defined to return an optional (i.e. null is ok). This seems like an advantage for using static instead - so invalid data received from an API can be discarded by the static method, and allowed to return null, rather than constructing a "token"/skeleton instance just to meet the return-value requiement of a factory - and then higher layers (e.g. the UI) can do a simple null-check on the return value of the static method rather than having to null-check each property (or, if the instances are going into a List, the nulls can just be omitted). Also means my model classes don't have to be defined as having optional members, to allow for constructing an instance from missing/corrupted data from the API...

Does this make sense?

J. Courtland Colburn • 3 years ago

Thanks for this article. I knew I had seen some of these features using factory, but couldn't find them in the Dart feature tour.

Yanko Diev • 4 years ago

Thank you for the article. However, this seems no longer valid...
....
Static(); // OK, likely a mistake