使用 Query 检索 CollectionGroup 并使用 Flutter 中的 Factory 将数据添加到动态列表

Retrieve CollectionGroup Using Query and adding the data to a dynamic List using Factory in Flutter

我正在尝试使用工厂将 FirebaseFirestore 中名为 'songs' 的 CollectionGroup 中的数据保存到动态列表中。我有一个名为 'getAllSongsFromCloud()' 的方法和一个名为 'Song' 的 Class 方法,它们使用工厂。 我的数据库结构如下所示。

我有一个名为 'artists' 的 collection,其中的每个文档都有一位艺术家, 然后每个艺术家都有一个名为 'songs' 的 collection。这是我感兴趣的带有歌曲类型文档的collection。

这是一个代码片段

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,
);
} 
}

这是我要存储数据'Song'类型的列表

 List<Song> _songs = [];

 List<Song> getAllSongs() {
 return [..._songs];

}

这是我用来查询所有 collection 数据的方法 'songs' 并将它们添加到名为“_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);

  });
  }

这是我打印列表“_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']

如果你得到 [Instance of 'Song'...] 是因为解析操作正确。如果您想在 print() 中看到歌曲包含,您需要在 Song class.

中覆盖 toString() 方法