Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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>

like image 784
EdYuTo Avatar asked Oct 15 '25 04:10

EdYuTo


1 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);
  }
});
like image 154
Michael Yuwono Avatar answered Oct 17 '25 17:10

Michael Yuwono



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!