如何将一个对象映射到 flutter dart 中不同类型的对象?

dev*_*uaz 2 mapping dart flutter

有什么方法可以将对象(例如PersonModel)映射到flutter dart 中的PersonEntity吗?

dev*_*uaz 6

这就是我目前进行这种映射的方式,首先我为映射器声明一个接口(抽象类):

abstract class Mapper<FROM, TO> {
  TO call(FROM object);
}
Run Code Online (Sandbox Code Playgroud)

然后,我为任何模型、实体制作自定义映射器,如下所示:

class ToSource implements Mapper<SourceModel, Source> {
  @override
  Source call(SourceModel object) {
    return Source(
      id: object.id,
      name: object.name,
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

用法如下:(将 SourceModel 类映射到 Source 类)

final toSourceMapper = ToSource();

final sourceModel = SourceModel(id: 'f4sge248f3', name: 'bbc news');
final source = toSourceMapper(sourceModel);
Run Code Online (Sandbox Code Playgroud)

如果还有另一种更好的方法来做这样的事情,请在下面回答..这对所有人都有帮助。