您应该将状态值放在 Riverpod 的什么位置?

问题描述

要访问 StateProvider 或 StateNotifierProvider 的状态:

有时在 Riverpod 文档中,状态变量会添加到 watch 函数之后。

int count = watch(counterProvider).state;

但是,我使用 StateNotifier 的代码仅在我在 watch 中引用它时才有效。即

watch(myNotifier.state)

有什么区别?

解决方法

在这两种情况下,使用提供程序的小部件的行为会有所不同。

在第一种情况下:

watch(counterProvider).state

消费者将查看整个 counterProvider,如果有任何原因导致 NotifyProvider,它将被重建。

第二种情况:

watch(counterProvider.state)

消费者只查看状态变量,只有在状态发生变化并导致 NotifyProvider 时才会重建。