Reputation: 331
I am trying to save data from a CollectionGroup called 'songs' in my FirebaseFirestore to a dynamic list using a Factory. I have a method called 'getAllSongsFromCloud()' and a Class called 'Song' that makes use of a Factory. My Database structure looks like this.
I have a collection called 'artists' and each document in there is an artist, Each artist then has a collection called 'songs'. And this is the collection with documents of type song that I am interested in.
Here's a code snippet
class Song {
final String cTitle, cPic, id, cPrice;
final int cQuantity;
Song({
required this.cTitle,
required this.cPic,
required this.cPrice,
required this.id,
required this.cQuantity,
});
factory Song.fromJson(Map<String, dynamic> json) {
return Song(
cTitle: json['title'],
cPic: json['songPoster'],
cPrice: json['price'], id: json['id'],
cQuantity: 1,
);
}
}
This is the list of type 'Song' in which I want to store the data
List<Song> _songs = [];
List<Song> getAllSongs() {
return [..._songs];
}
and here is the method I'm using to query the data from all collections called 'songs' and add them to a list called '_songs'
Future<void>getAllSongsFromCloud()async {
FirebaseFirestore? _instance;
_instance = FirebaseFirestore.instance;
Query<Map<String, dynamic>> songs = _instance.collectionGroup('songs');
QuerySnapshot<Map<String, dynamic>> snapshot = await songs.get();
snapshot.docs.forEach((item){
Song sng = Song.fromJson(item.data());
_songs.add(sng);
});
}
This is what I get when I print the list '_songs'
flutter: [Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song', Instance of 'Song']
Upvotes: 0
Views: 176
Reputation: 1624
If you get [Instance of 'Song'...]
is because the parse operation worked right. If you want to see Song contains in your print()
you need to override toString()
method in your Song
class.
Upvotes: 2