Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add json support for class Card #5

Closed
simphotonics opened this issue Apr 30, 2024 · 1 comment · Fixed by #6
Closed

Add json support for class Card #5

simphotonics opened this issue Apr 30, 2024 · 1 comment · Fixed by #6
Assignees

Comments

@simphotonics
Copy link

This enhancement request is related to this question on stackoverflow.

  • Add a method toJson() or a getter toJson:
/// Returns a map representation of this.
  Map<String, dynamic> get toJson => {
        'due': due.toIso8601String(),
        'stability': stability,
        'difficulty': difficulty,
        'elapsedDays': elapsedDays,
        'scheduledDays': scheduledDays,
        'reps': reps,
        'state': state.toString(),
        'lastReview': lastReview.toIso8601String()
      };
  • Add a constructor Card.fromJson:
/// Converts a map to an object of type `Card`.
factory Card.fromJson(Map<String, dynamic> json) {
    // Validate input
    if (json
        case {
          'due': String due,
          'stability': double stability,
          'difficulty': double difficulty,
          'elapsedDays': int elapsedDays,
          'scheduledDays': int scheduledDays,
          'reps': int reps,
          'state': String state,
          'lastReview': String lastReview
        }) {
      return Card()
        ..due = DateTime.parse(due)
        ..stability = stability
        ..difficulty = difficulty
        ..elapsedDays = elapsedDays
        ..scheduledDays = scheduledDays
        ..reps = reps
        ..state = State.values
            .firstWhere((element) => element.toString() == state.toString())
        ..lastReview = DateTime.parse(lastReview);
    } else {
      throw JsonUnsupportedObjectError(json,
          cause: 'In CardHelper.fromJson: '
              'Validation failed!');
    }
 }
  • Override the == operator and the method hashCode such that two Card objects are equal if all their fields are equal (see package equatable). That way the original object and the de-serialized object are equal.
@sonbui00 sonbui00 self-assigned this May 1, 2024
sonbui00 added a commit to sonbui00/dart-fsrs that referenced this issue May 1, 2024
sonbui00 added a commit that referenced this issue May 1, 2024
Feat: add support json for card class #5
@sonbui00
Copy link
Member

sonbui00 commented May 1, 2024

@simphotonics I added new code to support json. Please try in version 1.1.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants