flutter Riverpod将ref.watch作为参数传递

mtb9vblg  于 2023-05-08  发布在  Flutter
关注(0)|答案(1)|浏览(211)

在Riverpod中,我可以通过ref.read,它是“Reader”类型。
如何通过“ref.watch”,它的类型是什么?从源代码中我找不到。
通过“www.example.com”是不好的做法吗ref.watch?
谢谢

e0bqpujr

e0bqpujr1#

这不是一个好的做法,通过ref.watch作为你的问题。ref.watch的目的是“观察”状态的变化并重新构建,因此,通常ref.watch会进入小部件(ConsumerWidgets)的构建中。
总而言之,我想知道你为什么要通过。
我想你需要这样的解决方案阅读其他供应商,正确的?
可以只将ref作为参数传递,以允许类读取其他提供程序。通过引用,您可以创建ref.watch和ref.read,但是,请注意在哪里使用ref.watch,因为不建议在提供程序本身内部使用它。查看Riverpod详细文档here
例如,如果您创建一个提供程序来保存应用的整个逻辑,则可以创建一个从提供程序获取ref值的类,如下所示:

final createController = Provider((ref) => CreateProvider(ref));

class CreateProvider {

    CreateProvider(this.ref) {
        _init();
    }

    //Init to initialize values
    _init() async {

    }

    //Ref to access other providers
    final Ref ref;

}

有了ref,就可以访问在提供程序Scope中注册的其他提供程序。

相关问题