在阅读了文档之后,它并没有很好地解释ref.read()、ref.watch()和ref.listen()是什么。
我的问题如下:
发布于 2022-04-12 13:43:19
这些功能的目的和区别是什么?
读()
使用read只获取一次/in提供程序的值(一次读取)
表()
第一次和每次值更改时使用watch获取/in provider的值(查看它,就像订阅提供程序一样,因此每当发生更改时都会收到通知)
听()
listen类似于watch。主要的区别是返回类型。watch直接返回新值,listen返回一个void,但通过回调提供对新值和旧值的访问(参见下面的示例)
我可以在哪里,哪里不能使用这些函数?
您可以在一些地方使用read,如initState、回调(如onPressed等)。不应该异步调用watch和listen,比如在ElevatedButton的onPressed中。也不应在initState和其他国家生命周期中使用。
正如卡安·塔哈·科肯指出的那样:
避免使用read创建具有永不更改的值的小部件,考虑使用使用提供者或
select过滤不必要的重构。
我什么时候应该使用这些函数?
读()
如果您只想对提供程序的值进行一次评估,请使用read。
表()
当您希望始终获得值时,请使用watch。
示例:带有StateProvider的计数器应用程序
final counterProvider = StateProvider((ref) => 0);
class HomePage extends ConsumerWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final counter = ref.watch(counterProvider);
ref.listen(
counterProvider,
(previous, next) {
print("The new value is $next");
if (next == 5) {
print("I just reached 5");
}
},
);
return Scaffold(
body: Center(
child: Text(
counter.toString(),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
ref.read(counterProvider.state).state += 1;
},
),
);
}
}上面的示例显示了watch、read和listen的用法。
watch的counter值进行修改,以便在UI中随时更新它。listen到counter打印更新的值,并在I've reached 5为5时打印I've reached 5。read提供程序状态,并在按下FloatingActionButton时添加FloatingActionButton。https://stackoverflow.com/questions/71813090
复制相似问题