问题
Why won't the program wait for the function to return the list before going to the print statement?
I think it's because I made the forEach loop async but I need it to be async to get the newSummary which is a Future.
Future syncToCloud() async{
final List<Map<String,dynamic>> _events = await events();
print(_events.length);
}
Future<List<Map<String, dynamic>>> events() async {
List<Map<String, dynamic>> maps = await db.query('data');
List<Map<String, dynamic>> newMaps=[];
maps.forEach((element)async{
Map<String, dynamic> newElement = {};
if(element['summary']!=''){
newElement['summary'] = await newSummary(element['summary']);
print(newElement['summary']);
}
else{
newElement['summary'] = element['summary'];
}
newMaps.add(newElement);
});
return newMaps;
}
void main()async{
await syncToCloud();
}
回答1:
You're executing your return [{'hi':5}]
in a callback which wouldn't work. You should await the Future.delayed then return the List like this await Future.delayed(Duration(seconds: 2));
.
Future syncToCloud() async{
final List<Map<String,dynamic>> _events = await events();
print(_events.length);
}
Future<List<Map<String, dynamic>>> events() async {
await Future.delayed(Duration(seconds: 2));
return [{'hi':5}];
}
void main()async{
await syncToCloud();
}
回答2:
Please replace the following
maps.forEach((element)async{
Map<String, dynamic> newElement = {};
if(element['summary']!=''){
newElement['summary'] = await newSummary(element['summary']);
print(newElement['summary']);
}
else{
newElement['summary'] = element['summary'];
}
newMaps.add(newElement);
});
with this
await Future.wait( maps.forEach((element)async{
Map<String, dynamic> newElement = {};
if(element['summary']!=''){
newElement['summary'] = await newSummary(element['summary']);
print(newElement['summary']);
}
else{
newElement['summary'] = element['summary'];
}
newMaps.add(newElement);
}));
来源:https://stackoverflow.com/questions/62734766/flutter-await-not-waiting