Flutter Await not waiting

北城余情 提交于 2021-02-11 18:00:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!