google / google/json_serializable.dart

Holding a list of interface type while implementing this interface in different classes

Open
#1,019 5 comments 0 reactions 0 assignees View on GitHub
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

Hey guys,

I have the following use case and cannot resolve it. Maybe you got an idea whats wrong.
In general this is a quiz, the quiz has different types of questions like multiple choice, simple input and so on.
To get a list of Questions with these different types I have started to declare it as the following.

I can't generate successfully the fromJson method for IQuestion. But I dont get the problem as I just want to use it as Base to provide the properties to the different Question-Classes as well as holding all different question types in one List.

Maybe you got an idea what I am doing wrong as I am new to the json_serializable annotation as well as freezed.

Errorcode:

```
Could not generate `fromJson` code for `questions` because of type `IQuestion`.
package:greenzorro/domain/models/carbon_questionnaire.freezed.dart:40:23

40 │ List get questions => throw _privateConstructorUsedError;
│ ^^^^^^^^^

```

## Class that holds the list of questions
```dart
@freezed
@JsonSerializable(explicitToJson: true)
class Questionnaire with _$Questionnaire {
factory Questionnaire({
required List questions,
}) = _Questionnaire;

factory Questionnaire.fromJson(Map json) =>
_$QuestionnaireFromJson(json);
}
```

## Interface
```dart
abstract class IQuestion {
IQuestion({this.question, this.type, this.category, this.subCategory});
String? question;
Type? type;
Category? category;
String? subCategory;
}
```

## Implementations of Questions
There are some more but this should explain the problem.

```dart
@JsonSerializable(explicitToJson: true)
@freezed
class SimpleInputQuestion with _$SimpleInputQuestion {
@Implements(IQuestion)
factory SimpleInputQuestion({
Category? category,
String? question,
String? subCategory,
Type? type,
}) = _SimpleInputQuestion;

factory SimpleInputQuestion.fromJson(Map json) =>
_$SimpleInputQuestionFromJson(json);
}

@JsonSerializable(explicitToJson: true)
@freezed
class SimpleMultipleChoiceQuestion with _$SimpleMultipleChoiceQuestion {
@Implements(IQuestion)
factory SimpleMultipleChoiceQuestion({
Category? category,
String? question,
String? subCategory,
Type? type,
required List answers,
}) = _SimpleMultipleChoiceQuestion;

factory SimpleMultipleChoiceQuestion.fromJson(Map json) =>
_$SimpleMultipleChoiceQuestionFromJson(json);
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.