Flutter: Using JsonSerializable with inheritance with clean architecture
Asked Answered
V

0

6

I am trying to follow the Clean Architecture via this YouTube tutorial and because of that I have a set of models objects in the data layer that extends the entities objects.

Since I have many models, some of which having many fields, I wish to use json_serializable package in order to auto generate the boilerplate code that are the factories and relevant toJson and fromJson converters methods.

However when running:

flutter pub run build_runner build

It fails:

[SEVERE] Could not generate fromJson code for servers because of type Server.

My data architecture is as follow, in the data layer:

- HostModel extends Host(Entity)
    - String name,
    - List<ServerModel> servers,

- ServerModel extends Server(Entity)
    - ... // many many fields

However I managed to make it work if and only if all entities classes are annotated with @JsonSerializable(explicitToJson: true).

This is quite troubling to me as I am learning that the Clean Architecture separates all concerns via layers and follow the SOLID principles. So I believe entities should not be "aware" of the raw models. And the de/serialisation method should be substituable with any other method such as XML, a principle clearly violated here.

How can I solve the issue? Thanks for the help!

Veracruz answered 17/10, 2021 at 12:9 Comment(2)
Did you manage to find any solution?Dempsey
Nope. Still using the workaround explained in my post. However I was told there could an extra layer for a mapper which transforms the data model to the entity model, thus removing the need for inheritance. This can be useful if the backend endpoints provide complex json nodes from which you extract what you need for your ui / domain. Especially when backend is not front oriented.Veracruz

© 2022 - 2024 — McMap. All rights reserved.