I am learnign firebase , here i have just added some data to firebase collection but now i am failing to make factory constructor for getting data from fire base as document snapshot as i dont know how to deal for converting documentSnapshot to model class
thanks if you can implement and code for factory constructor
class Movie {
String id;
String name;
Movie({required this.id, required this.name});
toJson() {
return {
'Id': id,
'Name': name,
};
}
}
class MovieCategory {
String id;
String name;
List<Movie> movies;
MovieCategory({required this.id, required this.name, required this.movies});
toJson() {
return {
'Id': id,
'Name': name,
'Movies': movies.map((e) => e.toJson()).toList(),// check also this..is it ok?
};
}
factory MovieCategory.fromSnapshot(
DocumentSnapshot<Map<String, dynamic>> document) {
//dont know how to code for this..and it should return empty object if data is null..
}
}
List<MovieCategory> movieCategoryList = [
MovieCategory(
id: '1',
name: 'BollyWood',
movies: [
Movie(id: '1', name: 'Hindi 1'),
Movie(id: '2', name: 'Hindi 2'),
],
),
MovieCategory(
id: '2',
name: 'HollyWood',
movies: [
Movie(id: '1', name: 'English 1'),
Movie(id: '2', name: 'English 2'),
],
)
];
4
Answers
add this to your MovieCategory class
and aslo fromMap method to your Movie class
Extract the map from document and use it same, like you do with regular fromMap/fromJson method:
Data obtained from Firebase in the snapshots is in the form of a JSON
Map<String, dynamic>
, which could have as many nested fields, i.e. those "dynamic" values could be of any type including otherMap<String, dynamic>
.The easiest way for dealing with this is letting the library json_serializable just generate the code for you by annotating you class. This way you avoid forgetting adding fields or errors and typos.
Then wherever you are getting your document snapshot:
The MovieCategory class now includes the fromSnapshot factory constructor, which enables the conversion of a DocumentSnapshot from Firestore into a MovieCategory object.