I did find the answer to my question.
So in order to use the json_serializable
for the remaining ClassA
properties I have to use the @JsonKey
annotation for the property List<ClassB>
. By doing this, I can then use custom fromJson/toJson
methods. In this methods I can transform myList
to an appropriate Map for Firestore.
This is how I have to use it:
@JsonKey( fromJson: _firestoreMapToList, toJson: _listToFirestoreMap)
final List<ClassB> myList;
The methods _firestoreMapToList
and _listToFirestoreMap
will "override" the automatically generated methods of the classA.g.dart
file, which is also automatically generated when using the json_serializable
library and entering this flutter pub run build_runner watch
in the terminal.
This is how the methods exactly look like:
static List<ClassB> _firestoreMapToList(Map<String, dynamic> firestoreMap) {
if (firestoreMap != null) {
return List<ClassB>.from(firestoreMap?.entries
?.map((e) => ClassB.fromJson(e.value))
?.toList());
}
return null;
}
static Map<String, Map<String, dynamic>> _listToFirestoreMap(List<ClassB> list) {
if (list != null) {
return Map<String, Map<String, dynamic>>.from(list?.asMap()?.map(
(key, classB) => MapEntry(
classB.firebaseId,
classB.toJson())))
..removeWhere((key, value) => key == null); // remove map entries with null as key
}
return null;
}