作者:坚果 公众号:"大前端之旅" 华为云享专家,InfoQ签约作者,阿里云专家博主,51CTO博客首席体验官,开源项目GVA成员之一,专注于大前端技术的分享,包括Flutter,小程序,安卓,VUE,JavaScript。
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));
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有