我有一些模型需要将它们映射到JSON,反之亦然。因此,我遵循了flutter的JSON and serialization指南中的操作方法。
我发现自己为每种模型编写了相同的代码库,如下所示:
import 'package:flutter/material.dart';
import 'package:json_annotation/json_annotation.dart';
part 'folder_entity.g.dart';
@JsonSerializable(explicitToJson: true)
class FolderEntity {
final String id;
final String path;
bool isSelected;
FolderEntity({
@required this.id,@required this.path,this.isSelected = false,});
factory FolderEntity.fromMap(Map<String,dynamic> json) => _$FolderEntityFromJson(json);
Map<String,dynamic> toMap() => _$FolderEntityToJson(this);
}
我考虑过将fromMap
和toMap
移到名为Entity
的新抽象类中,但是由于两个原因,我无法这样做:
- 我无法扩展
factory
,因此我为每种方法编写了相同的模式。 - 我不确定是否可以将前缀从
_$FolderEntity
更改为_$Entity
,如果仍然可用,它甚至可以工作吗?