[请帮助我理解,为什么此代码不起作用!我尝试从流(Firestore)中获取数据,并将这些数据带到列表中。我想等到列表准备好之后,再用此列表执行操作。但是.then或.whenComplete在列表准备好之前会触发...这是制作列表并返回它的功能:
Future<List<EventDistance>> getEventsDistanceList(String eventId) async{
Stream<FS.QuerySnapshot> qs = EventDistanceDataRepository().getStreamByEventId(eventId: eventId);
List<EventDistance> dList = [];
EventDistance eventDistance;
qs.forEach((document) {
document.forEach((docs) {
eventDistance = eventDistanceFromJson(docs.data());
dList.add(eventDistance);
print(eventDistance.Name); //(3.) only for testing, to see if docs is not empty
}
);
});
print('return'); //(1.) only for testing, to see when return is fired
return dList;
}
(返回之前也会触发)我使用此代码是这样的:
Future<List<EventDistance>> dList = getEventsDistanceList(filteredList[index].id );
dList.then((value) {
print('value: $value'); //(2.) only for testing,to see if the returned list is empty or not (empty :-( )
doSomething;
});
[我跑步时,我先获得'return'(1.),然后获得'value:null'(2。)(还有一个空列表),然后获得列表的元素(Name1,Name2 ...)(3 )。我怎么了如何等待首先收到清单?感谢您的回答!
您需要在异步函数中使用await。我猜
Stream<FS.QuerySnapshot> qs =
EventDistanceDataRepository().getStreamByEventId(eventId: eventId);
应该是
Stream<FS.QuerySnapshot> qs = await
EventDistanceDataRepository().getStreamByEventId(eventId: eventId);
在需要很长时间的操作处获得await关键字。Try the code labs to get better with async await