riverpod icon indicating copy to clipboard operation
riverpod copied to clipboard

Request to add update state method to Notifier

Open shashkiranr opened this issue 2 years ago • 4 comments

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);

shashkiranr avatar Nov 13 '23 04:11 shashkiranr

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

rrousselGit avatar Nov 13 '23 09:11 rrousselGit

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.

shashkiranr avatar Nov 14 '23 19:11 shashkiranr

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;
}

AhmedLSayed9 avatar Nov 14 '23 22:11 AhmedLSayed9

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.

shashkiranr avatar Nov 14 '23 23:11 shashkiranr

The state is voluntarily protected.

I may add a StateProvider equivalent using codegen in the future, but not on all Notifiers.

rrousselGit avatar Mar 01 '24 11:03 rrousselGit