skip to Main Content

I want to filter out certain elements inside a stream that emits a list of elements.
For example a simple model (Item) that is the element inside the List:

class Item {
  int id;
  String title;
  bool isDone;
}

Then I´ve implemented a Riverpod provider that receives a List from some Service as a stream where I want to filter out certain Items based on one of its properties:

@riverpod
Stream<List<Item>> notDoneItems(NotDoneItemsRef ref) async* {
  // Get a list of Items as a stream from a service provider.
  final list = ref.watch(listItemsServiceProvider).listItems();

  // list = list.where(...) now I want to filter out all Items in the list
  // where isDone==true, so that only a list of items with isDone==false is returned

  yield* list;
}

My question is: I´m receiving a List here and I´m not able to use .where(). How should the syntax look like when trying to achieve a filter function inside a stream?

3

Answers


  1. Chosen as BEST ANSWER

    Thanks guys! Here´s the final solution that worked for me:

    @riverpod
    Stream<List<Item>> notDoneItems(NotItemsRef ref) async* {
      final list = ref.watch(listItemsServiceProvider)listItems();
      final newList = list.map((itemList) => itemList.where((item) => item.doneAt == null).toList());
      yield* newList;
    }
    

  2. Looks like the list variable is actually a Stream<List<Item>>, so you need to map it to a new stream using the map method and do the filtering inside:

    list.map((actualListAndNotAStream) => actualListAndNotAStream.where((element) => !element.isDone));
    
    Login or Signup to reply.
  3. Since you’re already in a Stream Provider, you can do the filtering using an explicit stream generator:

    Stream<T> build() async* {
      await for (final e in ref.watch(listItemsServiceProvider).listItems()) {
        if (e meets some filtering) yield e;
      }
    }
    

    That essentially open-codes what where does, but with many fewer parens. 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search