gpt4 book ai didi

firebase-realtime-database - Flutter firebase 数据库迭代项目

转载 作者:IT王子 更新时间:2023-10-29 06:55:11 26 4
gpt4 key购买 nike

我想知道如何从 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;
}

请有人帮助我。

最佳答案

对于有同样问题的人,我得到了这个工作:

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 = '';
}
}
}

谢谢大家

关于firebase-realtime-database - Flutter firebase 数据库迭代项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50652007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com