In this post, we will see how to resolve How to get a subset of items from a list in an AsyncNotifierProvider in Riverpod 2.0?
Question:
I have recently started using Riverpod 2.0 but I’m constantly running into the following issue / limitation which I dont know how to solve neatly. I will illustrate this using the code from the docs as found on the Riverpod 2.0 Docs for the NotifierProvider.The
AsyncTodosNotifier
contains a state with a list of Todo
items, all of which have their fields. Now lets suppose I want to have a screen with just a list of all completed Todos. How can I accomplish this in a provider, rather than push this code to the build
method of the widget. The latter not being reusable, not easily testable and not optimized in rendering.Here the code that accomplishes the task. But the filtering happens within the
.when()
in the build
method, which is not the place I would like this to happenAsyncNotifierProvider
or FutureProvider
which re-uses the data fetched by the main AsyncNotifierProvider
which will hold the state of all items.Best Answer:
Got some help from the Riverpod Discord server.The answer is to setup another provider that listens to the
.future
value of the original AsyncNotifierProvider
.So in this case:
If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com