将实时数据库中的数据检索到列表视图中



这是我的文件song.dart

class Song {
final String title;
final String singer;
final String cover;
final String url;
Song(this.title, this.singer, this.cover, this.url);
Song.fromJson(Map<String, dynamic> json)
: title = json['title'],
singer = json['singer'],
cover = json['cover'],
url = json['url'];
Map<String, dynamic> toJson() => {
'title': title,
'singer': singer,
'cover': cover,
'url' : url,
};
}

在main.dart上,这是我试图从实时数据库中获取数据的代码:

List musicList = <Song>[];
_MusicAppState() {
FirebaseDatabase.instance.reference().child("${getCurrentUID()}").once().then((DataSnapshot snapshot){
print("Sucessfully loaded the data");
snapshot.value.forEach((k,v){
musicList.add(v);
});
setState(() {
});
}).catchError((error) {
print("Failed to loaded the data");
});
}

同样在main.dart上,这是我试图在listview中显示数据的代码部分:

Expanded(
child: ListView.builder(
itemCount: musicList.length,
itemBuilder: (context, index) => customListTitle(
onTap: () {
playMusic(musicList[index]['url']);
setState(() {
_currentTitle = musicList[index]['title'];
_currentSinger = musicList[index]['singer'];
_currentCover = musicList[index]['cover'];
});
},
title: musicList[index]['title'],
singer: musicList[index]['singer'],
cover: musicList[index]['cover'],
),
),
),

我不知道为什么数据没有加载到listview中。但是,如果我删除List musicList = <Song>[];行中的<Song>,则数据将加载到listview中。如何使用<Song>将数据加载到列表视图中?因为我需要类Song来构建搜索功能,或者我可以在没有类Song的情况下构建搜索功能的任何其他方式?

您的musicList等待类型Song命名的类,但一旦该方法返回DataSnapshot类。您应该首先从DataSnapshot转换为Song类,如果您不知道如何转换,我正在解释。

你可以试试下面的代码;

final musicList = <Song>[];
FirebaseDatabase.instance.reference().child("${getCurrentUID()}").once().then((DataSnapshot snapshot){
print("Sucessfully loaded the data");
for(final snapshot in snapshot.value){
final songModel = Song.fromJson(snapshot as Map);
musicList.add(songModel);
}
setState(() {});
});

最新更新