Flutter Await不等待 [英] Flutter Await not waiting

查看:232
本文介绍了Flutter Await不等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在进入打印语句之前,程序不等待函数返回列表?

Why won't the program wait for the function to return the list before going to the print statement?

我认为这是因为我使forEach循环异步,但是我需要使其异步才能获得newSummary,这是一个Future.

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();
}

推荐答案

您正在不起作用的回调中执行返回[{'hi':5}] .您应该等待Future.delayed,然后像这样返回列表 await Future.delayed(Duration(seconds:2)); .

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();
}

这篇关于Flutter Await不等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆