I\'ve been investigating JSON parsing for my Flutter app and have a question about factory constructors that I can\'t resolve. I\'m trying to understand the advantage of usi
After I've been noticing and wondering the same, and given I don't think the other answers actually answer the question ("I've been investigating JSON parsing [...] I'm trying to understand the advantage of using a factory constructor verses a plain constructor"), here my try:
there's no advantage or difference that I could see or understand, when parsing json, in using a factory constructor instead of a plain constructor. I tried both, and both works fine, with all the types of parameters. I decided eventually to adopt the factory constructor, because of the convenience of how the code is written, and readability, but it's a matter of choice and both will work fine in all the cases.
null
. (However, some people dislike returning null from a factory constructor.)new
. (But using new is now discouraged.)async
. (A factory constructor must return a type of its class, so it cannot return a Future
.)const
.A normal constructor always returns a new instance of the current class (except when the constructor throws an exception).
A factory constructor is quite similar to a static method with the differences that it
new
but that is now less relevant since new
became optional.: super()
) So a factory constructor can be used
In your example this code
studentId: parsedJson['id'],
studentName : parsedJson['name'],
studentScores : parsedJson ['score']
could be moved to the body of a normal constructor because no final
fields need to be initialized.