31
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flutter(Dart)でListのforEachでasync, awaitを利用する時にはまったこと

Last updated at Posted at 2020-10-19

うまくいかなかった記述

①自分なりに実装

例1(list.forEachでasyncとawaitつけた)
void main() async {
  List<int> list = [1, 2, 3, 4, 5];
  
  // 1秒ごとに実行して欲しい
  list.forEach((num) async {
    await Future.delayed(Duration(seconds: 1));
    print(DateTime.now());
    print(num);
  });
  
  // ↑上の処理が終わったら実行して欲しい
  print(DateTime.now());
  print('Finish');
}
結果1(Finishが先になってしまい、ループ処理も1秒ごとじゃない)
2020-10-19 11:33:01.140
Finish
2020-10-19 11:33:02.141
1
2020-10-19 11:33:02.141
2
2020-10-19 11:33:02.141
3
2020-10-19 11:33:02.141
4
2020-10-19 11:33:02.142
5

②こちらの記事を参考に m(_ _)m

List.forEachでasync, awaitしたいならFuture.forEachを使おう

例2(list.forEach→Future.forEachに変更)
void main() async {
  List<int> list = [1, 2, 3, 4, 5];
  
  // 1秒ごとに実行して欲しい
  Future.forEach(list, (num) async {
    await Future.delayed(Duration(seconds: 1));
    print(DateTime.now());
    print(num);
  });
  
  // ↑上の処理が終わったら実行して欲しい
  print(DateTime.now());
  print('Finish');
}
結果2(1秒ごとにはなっているがまだFinishが先に来てる)
2020-10-19 12:06:42.782
Finish
2020-10-19 12:06:43.785
1
2020-10-19 12:06:44.789
2
2020-10-19 12:06:45.793
3
2020-10-19 12:06:46.795
4
2020-10-19 12:06:47.797
5

うまくいった記述

惜しかった...

例3(Future.forEachの前にawaitをつけた)
void main() async {
  List<int> list = [1, 2, 3, 4, 5];
  
  // 1秒ごとに実行して欲しい
  await Future.forEach(list, (num) async {
    await Future.delayed(Duration(seconds: 1));
    print(DateTime.now());
    print(num);
  });
  
  // ↑上の処理が終わったら実行して欲しい
  print(DateTime.now());
  print('Finish');
}
結果3
2020-10-19 12:09:46.037
1
2020-10-19 12:09:47.038
2
2020-10-19 12:09:48.040
3
2020-10-19 12:09:49.041
4
2020-10-19 12:09:50.042
5
2020-10-19 12:09:50.043
Finish
31
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?