Reputation: 250
I want to get all document in my firestore collection and then create Artist objects with it. I can get the data from firestore and display it, but when I add an artist to my list it remains empty
class Artist{
late String id;
late String name;
late String year;
Artist(this.id, this.name, this.year);
}
class ArtistsService{
Future getAllArtists() async {
Future<QuerySnapshot<Map<String, dynamic>>> firestoreResult = FirebaseFirestore.instance.collection('data').get();
late List<Artiste> localList = [];
FirebaseFirestore.instance.collection('data').get().then((docSnapshot) {
for (var i = 1; i <= docSnapshot.docs.length -1; i++) {
String id = docSnapshot.docs[i].id;
String annee = docSnapshot.docs[i]["annee"].toString();
String name = docSnapshot.docs[i]["artistes"].toString();
print(id); // It works
print(annee); // It works
print(name); // It works
localList.add(new Artiste(id,name,annee)); // It don't works
}
});
print("LIST : " + localList.toString());
return firestoreResult;
}
}
Data are print but list is empty, why?
I/flutter (27623): 3t36pe5ipPXxkhfh2lz7
I/flutter (27623): 2004
I/flutter (27623): Redrama
I/flutter (27623): 6lZTV9gu0DIlXCgxjVWu
I/flutter (27623): 2004
I/flutter (27623): Lars Horntveth
...
I/flutter (27623): LIST : []
Upvotes: 0
Views: 102
Reputation: 315
try change the line where you mention It don't works
to the code below. By doing this you are actually storing the value you get from docSnapshot into the variable of class Artiste
localList.add(
new Artiste(
id : id, // this id is the id that you get from docSnapshot
name : name, // this name is the name that you get from docSnapshot
year : annee, // this annee is the anne that you get from docSnapshot
)
);
Upvotes: 1