Home > Software design >  How to communicate between two stateProviders in river pod?
How to communicate between two stateProviders in river pod?

Time:02-03

i have just recently stated working with riverpod state mangement in flutter.

i have issue related to comunicate between to state providers.

here is my sample code:

class SomeClass_ONE extends stateNotifer <SomeState> {
SomeClass_ONE({required this.somevalue}):super(null);
  
  final SomeCustomClass somevalue;
  
  void methodOne(SomeState newstatevalue){
      state = newstatevalue;
 }
}


final someClassOneProvider = 
StateNotifierProvider<SomeClass_ONE,SomeState>.  
((ref)=>SomeClass_ONE(somevalue: SomeCustomClass()));

now i have another state provider class as below

class SomeClass_Two extends stateNotifer <SomeStateTwo> {
SomeClass_ONE({required this.somevalue}):super(null);

 final SomeCustomClass somevalue;

 void methodtwo(SomeState newstatevalue){
   state = newstatevalue;
  }

}

final someClassTwoProvider = 
StateNotifierProvider<SomeClass_Two,SomeStateTwo> 
((ref)=>someClassTwoProvider(somevalue: SomeCustomClass()));

now what i want to achhive is that on methodOne execution i have to listen that state cahnge and have to trigger methodTow and have to upate secondproviders state as well.

so how can i achive this without using Ref in class cunstroctors?

i have tried with ref.listner to trigger and have passed Ref in both class constructors. but as per some condition i can't use Ref directly in constructors as per some guideline followed by seniors.

CodePudding user response:

Try to use watch provided by StateNotifierProvider

Try this code:

class SomeClass_ONE extends stateNotifer <SomeState> {
  SomeClass_ONE({required this.somevalue}):super(null);
  
  final SomeCustomClass somevalue;
  
  void methodOne(SomeState newstatevalue){
    state = newstatevalue;
    // Listen to the changes in the state of the first provider and call the methodtwo of the second provider
    someClassTwoProvider.watch((_) => _.methodtwo(newstatevalue));
  }
}

CodePudding user response:

You can pass a Ref ref object to the methodtwo method and then call the necessary methods from other StateNotifierProvider. In any case, to refer to other methods of other classes, you need to have a Ref object.

  • Related