简化迭代逻辑

时间:2018-09-15 21:20:06

标签: dart

我有此代码有效。它正在遍历对象列表,并获得所有对象的一个​​属性存在于另一对象列表中的所有对象。

    List<WatchedGame> watching = List<WatchedGame>();
    for (WatchedGame watchedGame in watchedGames.list) {
      if (week.games.contains(watchedGame))
        watching.add(watchedGame);
    }

看来我可以简化此代码。

    List<WatchedGame> watching = watchedGames.list.where((watchedGame) {
      week.games.contains(watchedGame.game);
    });

但是我得到这个例外。

type 'WhereIterable<WatchedGame>' is not a subtype of type 'List<WatchedGame>'

1 个答案:

答案 0 :(得分:1)

在最后插入toList通话:

List<T> newList = list.where(condition).toList();