使用Flutter Riverpod时,如何从另一个Provider中访问一个Provider?

huangapple go评论58阅读模式
英文:

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

问题

You can access the updateMessage() method from Provider A in Provider B by using the read method to obtain the StateNotifier instance provided by Provider A. Here's how you can do it:

// In Provider B
final providerA = appMessageStateProvider.notifier;

// Now you can call updateMessage() from Provider A
providerA.updateMessage("Your message", messageType: AppMessageType.someType);

This way, you can access the method without involving the UI.

英文:

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

答案1

得分: 1

从任何提供者,您可以使用以下方式:

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

来调用其他提供者的通知器的方法。这不会建立依赖关系,并且按照常见惯例,所有这类方法都返回 void,因此这也不是让另一个提供者执行需要响应的操作的方法。

英文:

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.

huangapple
  • 本文由 发表于 2023年7月3日 02:53:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76600364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定