Search code examples
flutterdartstateriverpod

When using Flutter Riverpod, How do you access a provider from another provider?


I have defined a Riverpod State notifier provider(provider A), I have and then defined a method inside it's state notifier, and then I have defined Provider B, is there a way to access the method in Provider A, from Provider B without referencing the UI's WidgetRef?

// Provider A
final appMessageStateProvider = StateNotifierProvider.autoDispose<messageStateNotifier,
    AppMessage>((ref) {
  return messageStateNotifier();
});

// State notifier
class messageStateNotifier extends StateNotifier<AppMessage> {
  messageStateNotifier() : super(AppMessage(message: '', messageType: AppMessageType.normal));

  void updateMessage(String _message,{messageType = AppMessageType.normal}) {
    state = AppMessage(messageType: messageType, message: _message);
  }
}

and then I have the second provider below(Provider B)

final appSomthingStateProvider = StateNotifierProvider.autoDispose<appSomthingStateNotifier,
    AppMessage>((ref) {
  return appSomthingStateNotifier();// I then continued to define the state notifier
});


Now from Provider B, how do I access the method -> updateMessage() which is defined in provider A, without involving the UI


Solution

  • From any provider, you can use

    ref.read(otherProvider.notifier).notifierMethodHere(args);
    

    to invoke methods of the other provider's notifier. This does not set up a dependency relationship, and by common convention, all such methods return void, so this is also not a way to get another provider to perform actions that need responses.