[英]How can I map an object to different type of object in flutter dart?
Is there any way to map an object for instance PersonModel to PersonEntity in flutter dart?有什么方法可以将 map 和 object 例如PersonModel到PersonEntity中的 flutter ZBB14127678960FAE97D873950EA201?
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)用法如下:(将 SourceModel class 映射到 Source 类)
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.如果有另一种更好的方法来做这样的事情,请在下面回答..这对所有人都有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.