'converting entities into model in clean architecture in dart
As in clean architecture, we have to define the Entities in Domain layer and Models in Data layer. Now the issue that i am facing is in converting the entities into models when we are passing that as a request object in repositories.
here is the diagram which depicts the relationship amongst the entities (in brown) and models (in green).
Now, what is the simplest way to convert the entities to model in dart because implementing a mapper and then copy one field from another field seems a very tedious job and when there are nested objects in class (i.e. UserProfile data in below diagram) takes lots of time. so is there any library that exists or a better approach that could seamlessly convert entities to model.
abstract class Mapper<E, D> {
D mapFromEntity(E type);
E mapToEntity(D type);
}
Solution 1:[1]
You easily can convert from model to entity, if your model extends from your entity. Because, you do not need a mapper for this case actually. You pass fields to super() while initialisation.
class UserEntity {
final String id;
final String name;
final String surname;
final String? avatarImage;
UserEntity({required this.id, required this.name, required this.surname, this.avatarImage});
}
class UserModel extends UserEntity {
UserModel({
required String id,
required String name,
required String surname,
String? avatarImage,
}) : super(name: name, id: id, surname: surname, avatarImage: avatarImage);
Map<String, dynamic> toMap() {
return {
'id': this.id,
'name': this.name,
'surname': this.surname,
'avatarImage': this.avatarImage,
};
}
factory UserModel.fromMap(Map<String, dynamic> map) {
return UserModel(
id: map['id'] as String,
name: map['name'] as String,
surname: map['surname'] as String,
avatarImage: map['avatarImage'] as String,
);
}
}
final UserEntity user=UserModel.fromJson(someMap);
P.s. You can see also Converter<S,T> pre-made abstract class for mapping
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

