【问题标题】:Could I add formJson and toJson in this immutable class?我可以在这个不可变类中添加 formJson 和 toJson 吗?
【发布时间】:2021-02-16 18:44:13
【问题描述】:

我正在尝试做一个 Redux 记录器。我是 Flutter 的新手。

我安装了redux_logging 包,但在我的情况下它只打印Instance of <NameOfClass>

至于我在this answer 中阅读的内容,我可以打印数据,但需要在课堂上使用 toJson 和 fromJson。就是这样,简化

@immutable
class FetchState {
  final bool isError;
  final bool isLoading;

  FetchState({
    this.isError,
    this.isLoading,
  });

  factory FetchState.initial() => FetchState(
    isLoading: false,
    isError: false,
  );

  FetchState copyWith({
    @required bool isError,
    @required bool isLoading,
  }) {
    return FetchState (
      isError: isError ?? this.isError,
      isLoading: isLoading ?? this.isLoading   
    );
  }
}

我如何以及在何处添加 toJson 和 fromJson 以便能够使用 json.encode(fetchState) 打印实例中的变量(我想 fetchState 是 FetchState 的一个实例)

谢谢

【问题讨论】:

    标签: flutter debugging redux


    【解决方案1】:

    你需要这样声明

    class SkillHist {
      SkillHist({this.currentSkill, this.skillLevel, this.skillEarnedDate});
      int currentSkill;
      final List<int> skillLevel;
      final List<DateTime> skillEarnedDate;
    
      factory SkillHist.fromJson(Map<String, dynamic> json) {
        return SkillHist(
        currentSkill: json["currentSkill"] == null ? null : json['currentSkill'],
        skillLevel: json["skillLevel"] == null ? null : List<int>.from(json["skillLevel"].map((x) => x)),
        skillEarnedDate: json["skillEarnedDate"] == null ? null : List<DateTime>.from(json["skillEarnedDate"].map((x) => x)),
        );
      }
    
      Map<String, dynamic> toJson() => {
        "currentSkill": currentSkill == null ? null : currentSkill,
        "skillLevel": skillLevel == null ? null : List<int>.from(skillLevel.map((x) => x)),
        "skillEarnedDate": skillEarnedDate == null ? null : List<DateTime>.from(skillEarnedDate.map((x) => x)),
      };
    }
    

    https://quicktype.io 是一个很酷的网站,可以为给定的 JSON 自动生成代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 2019-08-21
      • 2019-11-23
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多