I'd like to know how to get a list of objects from a path on Flutter, here's how i get one object and works fine:
static Future<Year> getYear(
String yearKey) async {
Completer<Year> completer = new Completer<Year>();
FirebaseDatabase.instance
.reference()
.child("year")
.child(yearKey)
.once()
.then((DataSnapshot snapshot) {
var year = new Year.fromJson(snapshot.key, snapshot.value);
completer.complete(year);
});
return completer.future;
}
Now i am trying do this way to get a list of all years in the same path, but not know how iterage over items:
static Future<List<Year>> getYears() async {
Completer<List<Year>> completer = new Completer<List<Year>>();
List<Year> years = new List<Year>();
FirebaseDatabase.instance
.reference()
.child("year")
.once()
.then((DataSnapshot snapshot) {
//how to iterate over the items here?
completer.complete(years);
});
return completer.future;
}
Someone helps me please.
I got this working, for someone that have the same problem:
static Future<List<Year>> getYears() async {
Completer<List<Year>> completer = new Completer<List<Year>>();
List<Year> years = new List<Year>();
FirebaseDatabase.instance
.reference()
.child("year")
.once()
.then((DataSnapshot snapshot) {
//here i iterate and create the list of objects
Map<dynamic, dynamic> yearMap = snapshot.value;
yearMap.forEach((key, value) {
years.add(Year.fromJson(key, value));
});
completer.complete(years);
});
return completer.future;
}
Here is the Year code:
class Year{
String key;
String name;
Year({this.name});
Year.fromJson(this.key, Map data){
name = data['name'];
if(name == null){
name = '';
}
}
}
Thank you everyone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With