[英]Riverpod ref.watch(statenotifierprovider) vs ref.watch(statenotifierprovider.notifier)
I've been trying to find out what is the difference between watching a StateNotifierPovider
object vs watching the notifier exposed by it.我一直在试图找出观看StateNotifierPovider
object 与观看它暴露的通知程序之间的区别。 As we can see in the docs following section watching the notifier object does not trigger the object's build method when the state is changed.正如我们在以下文档中看到的那样,当 state 发生更改时,监视通知程序 object 不会触发对象的构建方法。 Out of experimenting, it seems like watching the provider object exposes the state within the notifier just as ref.read(provider.notifier)
.出于实验,似乎在观察提供者 object 在通知程序中公开 state 就像ref.read(provider.notifier)
一样。 state would. state 会。 I can't really get the difference between directly watching the provider vs provider.notifier
and why it does not trigger the build method when watching the notifier and changing its state.我无法真正理解直接观察提供者与provider.notifier
之间的区别,以及为什么它在观察通知程序并更改其 state 时不触发构建方法。
The documentation of .notifier
should hopefully be clear about it: .notifier
的文档应该很清楚:
Obtains the StateNotifier associated with this provider, without listening to state changes.获取与此提供者关联的 StateNotifier,而不监听 state 变化。
This is typically used to invoke methods on a StateNotifier.这通常用于调用 StateNotifier 上的方法。 For example:例如:
Button( onTap: () => ref.read(stateNotifierProvider.notifer).increment(), )
This listenable will notify its notifiers if the StateNotifier instance changes.如果 StateNotifier 实例发生变化,此可监听器将通知其通知程序。 This may happen if the provider is refreshed or one of its dependencies has changes.如果刷新提供者或其依赖项之一发生更改,则可能会发生这种情况。
https://pub.dev/documentation/riverpod/latest/riverpod/AutoDisposeStateNotifierProvider/notifier.html https://pub.dev/documentation/riverpod/latest/riverpod/AutoDisposeStateNotifierProvider/notifier.html
So ref.watch(provider)
listens to state changes.所以ref.watch(provider)
监听 state 变化。
And ref.watch(provider.notifier)
obtains the notifier only but does not listen to state change.而ref.watch(provider.notifier)
只获取通知器,不监听 state 变化。 Instead it listens to when the StateNotifier
instance is recreated – such as if you did ref.refresh(provider)
, which would recreate the StateNotifier
相反,它会监听何时重新创建StateNotifier
实例——例如,如果您执行了ref.refresh(provider)
,这将重新创建StateNotifier
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.