0

I am trying to do a Redux logger. I am new to Flutter.

I installed redux_logging package but in my case it just prints Instance of <NameOfClass>

As for what I am reading in this answer, I could print the data, but need to use toJson and fromJson in my class. This is it, simplified

@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   
    );
  }
}

How and where do I add toJson and fromJson in order to be able to print the variables in the instance using json.encode(fetchState) (where fetchState is an instance of FetchState I suppose)

Thank you

user3808307
  • 2,270
  • 9
  • 45
  • 99

1 Answers1

1

you need to declare it like this

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)),
  };
}

A cool site to get the code generated automatically for a given JSON is https://quicktype.io

w461
  • 2,168
  • 4
  • 14
  • 40