converting entities into model in clean architecture in dart
Asked Answered
K

1

6

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);
}

entity to model relationship

Krick answered 4/8, 2021 at 13:34 Comment(3)
I also want to know the simplest way to convert the entities to model in dart, any example code for this? anyone can guide us?Delorenzo
@Delorenzo i end up creating the mapper classes for model to entitiy and entitity to modelKrick
I ended up implementing Model.fromEntity(Entity e) factory constructors in model classes, which copy, one by one, values from the entity class (and calling respective fromEntity factory methods of nested classes, if needed). A bit tedious, yes, but at least it works, and does not break the CA design principles.Woodland
L
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

Loren answered 13/1, 2022 at 15:3 Comment(1)
The question was not about converting models to entities, but about converting entities to models. For outgoing requests, for example.Woodland

© 2022 - 2024 — McMap. All rights reserved.