0

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();
}
123432198765
  • 276
  • 3
  • 14

2 Answers2

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);
  }));
Sanjay Sharma
  • 3,687
  • 2
  • 22
  • 38
  • This works too! But changing the forEach to a for loop also worked and was a bit shorter. – 123432198765 Jul 04 '20 at 22:06
  • Using this exact code thrown this error: 'This expression has a type of 'void' so its value can't be used.' for `forEach` of a `List`. – mrahimygk Jan 18 '21 at 17:25
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();
}
JideGuru
  • 7,102
  • 6
  • 26
  • 48