Using a Factory Constructor for JSON serialization

Thanks for the great book!

I noticed in Ch. 6 that you use JSON serialization you use a factory constructor. In your explanation of the use of factory constructor, you write

“The thing to pay attention to now is that the factory constructor body allows you to perform some work before returning the new object, without exposing the inner wiring of that instantiation process to whoever is using the class.”

I am still a little confused on this point. I understand that you are just using serialization as an example of how people typically use factory constructors, but you could just as easily use a regular constructor for this similar to what we did earlier in the chapter. Would it be possible to add a little more information on why a factory constructor is better than a generative constructor for json serialization or a challenge question that teaches this point??

After reading the below links, I have a better idea but it’s not completely clear to me yet.

Thanks!!

(and others, but I was limited on the number of links that I can post)

Good question! I had a similar question when I was writing the book, and made a Stack Overflow Q&A about it:

However, that doesn’t exactly answer what you are asking here. I agree with lrn’s answer in your first link and I just finished writing a longer explanation about that answer. You can check it out here:

(lrn, by the way, is one of the Dart engineers working for Google, so he knows what he’s talking about.)

Feel free to ask any followup questions. In summary, though, I’d say that it really doesn’t matter that much which method you use most of the time.

Thank you for your question. This also helps me and other readers to learn more.

TODO: add more explanation in the next version of the book.

Thanks! This is really helpful. I think that in your first code block in your answer for the below question that you may have created a factory constructor, when you meant to create a generative constructor??

Oops! Yes, you’re right. Thanks for catching that. I updated the answer.

This is now covered in the upcoming book Dart Apprentice: Fundamentals chapter 9, “Constructors”.