Naduel
Naduel

Reputation: 83

In Riverpod 2.0 Flutter, is it possible to create multiple NotifierProvider?

Before Riverpod is using build_runner, it was possible to create multiple provider that using one class of (State)Notifier. like the code below,

class Counter extends StateNotifier<int>{
  Counter(): super(0);
  
  void increment() => state++;
}


final counter1Provider = StateNotifierProvider<Counter,int>((ref) => Counter());
final counter2Provider = StateNotifierProvider<Counter,int>((ref) => Counter());

Counter counter1 = ref.watch(counter1Provider);
Counter counter2 = ref.watch(counter2Provider);

Then the Riverpod is updated to 2.0 and now support code generation, the Counter class can be like this.

@riverpod
class Counter extends _$Counter {

  @override
  int build(){
    return 0;
  }

  void increment(){
    state ++;
  }


Counter counter = ref.watch(counterProvider);

It seems like the StateNotifier and StateNotifierProvider is became into one Provider, it possible to create another Provider that return the Counter class?

Upvotes: 1

Views: 273

Answers (1)

CNK
CNK

Reputation: 703

I'm not sure if this is what you need. With the new annotation, you only need the following to access to the class:

ref.read(counterProvider.notifier).increment();

This will call the increment() method into your notifier class.

Hope this can help.

Upvotes: 0

Related Questions