使用JsonSerialzable时如何避免在Flutter中重复

我有一些模型需要将它们映射到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);
}

我考虑过将fromMaptoMap移到名为Entity的新抽象类中,但是由于两个原因,我无法这样做:

  1. 我无法扩展factory,因此我为每种方法编写了相同的模式。
  2. 我不确定是否可以将前缀从_$FolderEntity更改为_$Entity,如果仍然可用,它甚至可以工作吗?
h11111_h 回答:使用JsonSerialzable时如何避免在Flutter中重复

对于第二个问题,应该在_$FolderEntity文件中将前缀从_$Entity更改为folder_entity.g.dart

本文链接:https://www.f2er.com/3139068.html

大家都在问