我想知道如何从Flutter上的路径获取对象列表,这里是我如何获得一个对象并且工作正常:
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;
}
现在我正在尝试以这种方式获取同一路径中所有年份的列表,但不知道如何迭代项目:
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;
}
有人帮助我。
答案 0 :(得分:1)
对于有相同问题的人,我可以使用它
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;
}
这是年份代码:
class Year{
String key;
String name;
Year({this.name});
Year.fromJson(this.key, Map data){
name = data['name'];
if(name == null){
name = '';
}
}
}
谢谢大家。