Is there any way to map an object for instance PersonModel to PersonEntity in flutter dart?
Simplest way:
void main() {
final model = PersonModel(id: 0, name: 'name0');
final entity = _convert(model);
print(entity);
}
final _convert = (PersonModel e) => PersonEntity(
id: e.id,
name: e.name,
);
class PersonEntity {
int id;
String name;
PersonEntity({this.id, this.name});
@override
String toString() => 'id: $id, name: $name';
}
class PersonModel {
int id;
String name;
PersonModel({this.id, this.name});
}
Result:
id: 0, name: name0
This is how I currently do that kind of mapping, first I declare an interface (abstracted class) for the mapper:
abstract class Mapper<FROM, TO> {
TO call(FROM object);
}
Then, I make the custom mapper for any models, entities like so:
class ToSource implements Mapper<SourceModel, Source> {
@override
Source call(SourceModel object) {
return Source(
id: object.id,
name: object.name,
);
}
}
And The usage would be like this: (mapping SourceModel class to Source class)
final toSourceMapper = ToSource();
final sourceModel = SourceModel(id: 'f4sge248f3', name: 'bbc news');
final source = toSourceMapper(sourceModel);
If there is another better way of doing such thing, answer below.. it would be helpful for all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.