LoginSignup
1
2

More than 1 year has passed since last update.

FlutterのforEachで「async/await」を使う

Posted at

早速結論ですが、Future.forEachを使います。

// 例: idでItemオブジェクトを取得してリストに格納する。
Future loadItems() async {

  List<Item> items = [];

  await Future.forEach(_ids, (id) async {
    // findByIdメソッドで、DBまたはWebAPIからitemオブジェクトを取得する。
    Item item = await _itemRepository.findById(id);
    items.add(item);
  });

  ...
}

最初は以下のように実装していたので、forEachの処理が終わる前に次の処理が呼ばれてました...。

// Bad!!
Future loadItems() async {

  List<Item> items = [];

  _ids.forEach((id) async {
    Item item = await _itemRepository.findById(id);
    items.add(item);
  });

  ...
}
1
2
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
1
2