Repository navigation
Closed
Description
A common use case is to trigger side-effects and have the UI listen to the status of that side-effect (such as showing a spinner/snackbar on error)
I don't think there is a neat way to support this without code-generation that wouldn't have fundamental flaws (like the inability to pass parameters).
But with the new code-generation syntax for providers, Riverpod should be able to support this
In particular, we could have:
@riverpod
class Example extends _$Example {
@override
Future<List<Todo>> build() => fetchTodoList();
@mutation
Future<void> addTodo(Todo todo) async {
await http.post(...., todo.toJson());
}
}which would then be used inside widgets by doing:
Consumer(
builder: (context, ref, child) {
// as usual, nothing special
List<Todo> todos = ref.watch(exampleProvider);
// our UI listens to "addTodo" side-effects.
// The returned AddTodoMutation object contains things like loading/error/result
// of the mutation, similar to that of AsyncValue.
AddTodoMutation addTodo = ref.watch(exampleProvider.addTodo);
return SomeButton(
// invoke the Example.addTodo method
onTap: () => addTodo(Todo())
);
},
)Mutations would also receive a custom ProviderObserver event for start/completion/failure, with an Invocation corresponding to the method invocation.
And of course, riverpod_graph & the devtool should be updated to show mutations
Reacted by Chris Wickens, Rodolfo Silva, Roberto Potrus, Ethan Hipps, Luca Venir, Muhammad Yusuf, Sáng Nguyen, Ortes, MiniSuperDev, Preston Schwartz and 36 more
Reacted by Tim Whiting, mono — Masayuki Ono, Ryan, Michael Barrett, birros, Khari Lane, mori yuta, Sam M.K, Agon Noga, 2IZI4U and 44 more
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or request
Activity
rrousselGit commentedon Sep 21, 2022
Tagged as "2.1" but likely will come after. Consider this as a "planned"
TimWhiting commentedon Oct 8, 2022
As a side note, the linter is too aggressive about read vs watch in provider definitions when you are using
FutureProviderfor mutations. (you don't always want to rerun a mutation when things change, in some cases it might make sense, but not always).rrousselGit commentedon Oct 8, 2022
You're not supposed to use FutureProvider for mutations to begin with.
AhmedLSayed9 commentedon Nov 26, 2022
Will this solve use cases when there's just a single mutation without the need of
build?i.e: a LoginProvider use case which might be a FutureProvider.
It will be triggered through
onPressedlater while you need to pre watch/listen to show a spinner/snackbar on error.Currently, This can be handled by 3 approaches:
1- Using StateNotifier or now AsyncNotifier with
AsyncValue<void>ornullableAsyncValue.2- Creating 3 providers:
FutureProviderthat trigger the call.StateProviderthat hold the login parameters which will be initially null.Providerthat return AsyncValue which will be initially AsyncData(null) and it'll watch for the second provider (login params) and will trigger the call when login parameters is submitted.3- Similar to second approach but instead of creating 3 providers, create just the main provider and handle what second and third providers is doing in the widget itself using Hooks or StatefulWidget.
Update: 3rd approach looks much complicated and will include unnecessary rebuilds of the widget, 1st approach is not favorable and is hard to maintain later. so I think the 2nd approach of combining 3 providers is the way to go (at least for now).
AhmedLSayed9 commentedon Nov 27, 2022
Edit: check my updated approach.
This an example of the 2nd approach using the 3 providers (which was recommended before on Discord):
Result:
Screen.Recording.2022-11-28.at.1.24.34.AM.mov
This is same as login/register/logout/et. use cases.
It works great but looks like too much work to pre watch/listen a callable Future and act upon its state.
ruanwenfeng commentedon Dec 26, 2022
When can we use this amazing feature, very much looking forward to.
RodolfoSilva commentedon Feb 19, 2023
Whats is the best alternative until we have the
@mutation? @rrousselGit ?Right now I'm using the approach showed by @AhmedLSayed9.
RodolfoSilva commentedon Feb 19, 2023
We could also use this approach using flutter_hooks, like is made in the React world.
But I think this could always return a generic instance of Mutation:
And refactor the code like that:
I've not run this code, but I don't think this is working. The point here is to have an Idea of an workaround.
TekExplorer commentedon Feb 20, 2023
I currently use this provider for mutations (and yes, the
FutureOris necessary, though you could change it toFutureand mark it async)i then use it by providing the family with
final mutationKey = useMemoized(Object.new)you can also add whatever convenience methods you like, such as a
whenon the enum, or creating amutationWhenextension onAsyncValue<MutationEnum>which replacesdatawithinitialandsuccessTekExplorer commentedon Feb 20, 2023
you can always try and adjust it to return the success data if you want, but ideally you should be calling notifier methods from other providers that handle the data for you.
its used by
you could also save it as a callback somewhere
TekExplorer commentedon Feb 24, 2023
I've improved my approach a lot, with some suggestions by remi.
This mirrors the approach that the code gen solution will have, at least as far as api is concerned
https://github.com/TekExplorer/riverpod_mutations
it also includes a generic mutations provider.
chimon2000 commentedon Feb 24, 2023
An interesting solution I discovered last week
https://pub.dev/packages/rivertion
TekExplorer commentedon Feb 25, 2023
missing github link == yeet
chimon2000 commentedon Feb 25, 2023
14 remaining items
TekExplorer commentedon Dec 29, 2023
Not likely. It's possible to have multiple parameters that want to be keys. My solution uses an additional annotation called
@mutationKeyon the parameters in question that does this.ewilliams-zoot commentedon Dec 29, 2023
That actually makes sense - like a compound key for a database table. An additional annotation would seem to make the most sense in a solution like this then.
mrverdant13 commentedon Jan 9, 2024
I really find the initial @rrousselGit's proposal quite useful
Being able to discriminate among different mutation methods is currently not possible within a
ProviderObserver, which is often essential to register/post the mutation intent (as well as its payload and metadata) to an analytics manager/provider/service.In the meantime, the approach that best suits my requirements is the use of one
Notifierper each mutation method.The
Notifiermanages a custom variation of anAsyncValue, where theAsyncLoadingsubclass encloses the metadata related to the ongoing mutation.As a result, any
ProviderObservercan be fully aware of the mutation state as well as of its corresponding metadata/payload.Even better, the use of an
AnalyticsEventmixin class to mark those custom classes as such, which later on can be easily identified by the observer.My guess is that, one of the potential benefits that entails the introduction of the
@mutationannotation, is the capability to track them in a similar fashion as described above, but with the additional advantage of the proper automatic update of the rootAsyncNotifierstate.I opened a discussion entry looking for existing options for the specific use case I mention here, where I also included a simple example description, in case more context is required.
rrousselGit commentedon Jan 9, 2024
Yes, tracking what triggered a state change is in the scope of this issue.
I specifically am working on that for the devtool, but logging is another one.
RodolfoSilva commentedon Jul 11, 2024
Hook alternative:
@rrousselGit do you have any suggestion?
masreplay commentedon Jul 11, 2024
I created this simple package using Riverpod and Hook riverpod_hook_mutation
Define
Call
Usage
TekExplorer commentedon Jul 12, 2024
I wouldn't have named it that. It's not riverpod specific.
Add mutations (#3860)
rrousselGit commentedon Dec 9, 2024
'tis done
So closing :)
dm-finvest commentedon Dec 30, 2024
Hey @rrousselGit, is this part of the latest 3.0 prerelease? I tried upgrading all the Riverpod packages to the latest 3.0 prerelease versions but the annotation
@mutationisn't detected.TekExplorer commentedon Dec 30, 2024
It's not published.
rrousselGit commentedon Dec 30, 2024
I've stopped publishing dev releases because they are too taxing for me. I'll likely make one after offline and some critical bugfixes
dickermoshe commentedon Sep 12, 2025
I don't see anyway of doing debouce which is a pretty basic requirement for mutations
rrousselGit commentedon Sep 12, 2025
That's not the purpose of mutations. But if we want those things, make a feature request :)