I'm a beginner so this question may sound trivial to you experts but i'm unable to understand the concept here. pls help In the Flutter Fire documentation, in CollectionReference and DocumentReference segment
Movie({required this.title, required this.genre});
Movie.fromJson(Map<String, Object?> json) // Here Movie.fromJson is created
: this(
title: json['title']! as String,
genre: json['genre']! as String,
);
final String title;
final String genre;
// What if i create fromJson like this. would it be valid?
// and upper function is just a simplified version of this
Object fromJson (Map<String, Object?> json) {
return (
title: json['title']! as String,
genre: json['genre']! as String,);
}
Map<String, Object?> toJson() { // Here toJson is created differently
return {
'title': title,
'genre': genre,
};
}
}
//Further they are used like this
final moviesRef = FirebaseFirestore.instance.collection('movies').withConverter<Movie>(
fromFirestore: (snapshot, _) => Movie.fromJson(snapshot.data()!),
toFirestore: (movie, _) => movie.toJson(),
);
Why fromJson and toJson are created differently
CodePudding user response:
toJson
converts Movie
to a Map
(to store in firestore), while fromJson
converts the Map
to the Movie
(for easy use in flutter).
withConverter helps retain type safety, by automatically converting firebase's Map
to Movie
and back.