Is it possible to filter a List with a function that returns Future?

Viewed 462

I have a list List<Item> list and a function Future<bool> myFilter(Item).

Is there a way to filter my list using the Future returning function myFilter()?

The idea is to be able to do something like this:

final result = list.where((item) => myFilter(item)).toList();

But this is not possible since where expects bool and not Future<bool>

4 Answers

Since the iteration involves async operation, you need to use a Future to perform the iteration.

final result = <Item>[];
await Future.forEach(list, (Item item) async {
  if (await myFilter(item)) {
    result.add(item);
  }
});

You can iterate over your collection and asynchronously map your value to the nullable version of itself. In asyncMap method of Stream class you can call async methods and get an unwrapped Future value downstream.

final filteredList = await Stream.fromIterable(list).asyncMap((item) async {
      if (await myFilter(item)) {
        return item;
      } else {
        return null;
      }
    }).where((item) => item != null).toList()

You can try bellow:

1, Convert List => Stream:

example:

Stream.fromIterable([12, 23, 45, 40])

2, Create Future List with this function

  Future<List<int>> whereAsync(Stream<int> stream) async {
    List<int> results = [];
    await for (var data in stream) {
      bool valid = await myFilter(data);
      if (valid) {
        results.add(data);
      }
    }
    return results;
  }

Try this:

    final result = turnOffTime.map((item) {
      if(myFilter(item)) {
        return item;
      }
    }).toList();
Related