Flutter Await不等待

编程入门 行业动态 更新时间:2024-10-26 04:23:17
本文介绍了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不等待

本文发布于:2023-11-06 09:56:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563376.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Flutter   Await

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!