填充之前的未来退货清单 [英] Future returns list before being populated
问题描述
我有以下方法:
Future<List<Job>> getUserJobs() async {
Query query = _firebaseDatabase
.reference()
.child("jobs")
.child(_firebaseAuth.currentUser.uid)
.orderByKey();
List<Job> userJobs = [];
if (query == null) {
return userJobs;
}
query.onValue.listen((event) {
Map<dynamic, dynamic> values = event.snapshot.value;
values.forEach((key, value) {
userJobs.add(Job.fromJson(key, Map.from(value)));
});
});
return userJobs;
}
我想在另一个类中获得此响应,但是,上述方法返回的列表始终为[].我检查了一下,并确实填充了userJobs列表,但是return语句之前已执行.
I want to get this response in another class, however, the list returned by the above method is always []. I checked and the userJobs list is indeed populated but the return statement is executed before.
数据库的结构为: 作业收集具有用户ID,对于每个用户ID,我有几个作业密钥(每个都有其作业数据).
The structure of the database is: Job collection has user IDs and for each user ID I have several job keys (each with its job data).
推荐答案
尝试一下:
Future<List<Job>> getUserJobs() async {
List<Job> userJobs = [];
// Query query =
await _firebaseDatabase
.reference()
.child("jobs")
.child(_firebaseAuth.currentUser.uid)
.once()
.orderByKey().then((result) async {
if (result.value != null) {
result.value.forEach((key, childSnapshot) {
userJobs.add(Job.fromJson(key, Map.from(childSnapshot)));
});
} else {
print(
'getUserJobs() no jobs found');
}
}).catchError((e) {
print(
'getUserJobs() error: $e');
});
// if (query == null) {
// return userJobs;
// }
// query.onValue.listen((event) {
// Map<dynamic, dynamic> values = event.snapshot.value;
// values.forEach((key, value) {
// userJobs.add(Job.fromJson(key, Map.from(value)));
// });
// });
return userJobs;
}
您的循环也需要是异步的.否则,该方法将在循环结束之前返回,并返回空的List ..
还总是使用.catchError
回调..它告诉您出了什么问题;)
your loop also needs to be async..otherwise the method will return before the loop finishes, returning the empty List.. been there and got quite frustrated by this..
also always use .catchError
callback.. it tells you what's going wrong ;)
这篇关于填充之前的未来退货清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!