Dart:在循环中使用 Async 和 Await作者:坚果 公众号:"大前端之旅" 华为云享专家,InfoQ签约作者,阿里云专家博主,51CTO博客首席体验官,开源项目GVA成员之一,专注于大前端技术的分享,包括Flutter,小程序,安卓,VUE,JavaScript。
在 Dart(以及 Flutter)中,您可以使用Future.forEach在循环中顺序执行同步操作。下面的示例程序将打印从 1 到 10 的数字。每次打印完一个数字,它会等待 3 秒,然后再打印下一个数字。 //大前端之旅 void main() async { final items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; await Future.forEach(items, (item) async { print(item); await Future.delayed(const Duration(seconds: 3)); }); }
另一种方法是在语法中使用for ... ,如下所示: // 大前端之旅 void main() async { final items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (int item in items) { print(item); await Future.delayed(const Duration(seconds: 3)); } }
|