In Firestore my documents are structured like this:
In this example the map lineup
has two children of type map
. There might be more and there might be zero for other docs.
I'm trying to convert the lineup
map of a DocumentSnapshot into a LineUp object generated by freezed.
This is my code so far:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:json_annotation/json_annotation.dart';
part 'line_up.freezed.dart';
part 'line_up.g.dart';
@freezed
abstract class LineUp with _$LineUp {
const factory LineUp({
required Map<String, dynamic> artistMap,
}) = _LineUp;
factory LineUp.fromDocumentSnapshot(DocumentSnapshot documentSnapshot) {
final Map<String, dynamic> parsed = documentSnapshot.data()?["lineup"];
print(parsed.toString()); //prints { p88U4b5lbAwouMVjjNZX: {trackId: 53, name: Name2}, fbei2rdwqBuMDTuFwY4m: {trackId: 23, name: Name1}}
return LineUp.fromJson(parsed); //Exception thrown: 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast
}
factory LineUp.fromJson(Map<String, dynamic> json) => _$LineUpFromJson(json);
}
Obviously something is missing since nowhere name
and trackId
is defined in the freezed class.