riverpod
riverpod copied to clipboard
Request to add update state method to Notifier
Is it possible to add updateState to Notifier just like it was present in StateProvider?
ref.read(provider.notifier).update((state) => state + 1);
Currently as per documentation the only way to get this is by adding the below to every Class Notifier. There are many Notifier<bool> that is used which will require the update function
T update(T Function(T state) cb) => state = cb(state);
I don't plan on doing so for now. You're supposed to add methods on your notifiers.
Even if I added it, this method would be protected anyway, so you'd get a warning if you did what you want
I understand the reason behind it but for Notifiers which hold single value of type int/ bool/ Enum, the update state would help in not repeating code in multiple notifiers.
I understand the reason behind it but for Notifiers which hold single value of type int/ bool/ Enum, the update state would help in not repeating code in multiple notifiers.
In that case, you can voluntarily use a simple mixin that do the job:
mixin NotifierUpdate<T> on Notifier<T> {
void update(T Function(T state) cb) => state = cb(state);
}
@Riverpod(keepAlive: true)
class Sample extends _$Sample with NotifierUpdate {
@override
int build() => 0;
}
I understand the reason behind it but for Notifiers which hold single value of type int/ bool/ Enum, the update state would help in not repeating code in multiple notifiers.
In that case, you can voluntarily use a simple mixin that do the job:
mixin NotifierUpdate<T> on Notifier<T> { void update(T Function(T state) cb) => state = cb(state); } @Riverpod(keepAlive: true) class Sample extends _$Sample with NotifierUpdate { @override int build() => 0; }
This is exactly what I am doing now. Also I have added set state since it is also protected. Having a built in update makes sense for single value notifiers.
The state is voluntarily protected.
I may add a StateProvider equivalent using codegen in the future, but not on all Notifiers.