您当前的位置: 首页 >  ar

大前端之旅

暂无认证

  • 2浏览

    0关注

    403博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Dart:在循环中使用 Async 和 Await

大前端之旅 发布时间:2022-04-21 23:22:15 ,浏览量:2

Dart:在循环中使用 Async 和 Await

img

在 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));
  }
}
关注
打赏
1660524863
查看更多评论
立即登录/注册

微信扫码登录

0.0446s