将提供者作为参数传递给小部件是最佳实践吗?
将提供者作为参数传递给小部件是最佳实践吗?
我知道我们可以从小部件内直接访问提供程序。 但看到几个代码片段将提供程序作为参数传递给子小部件。 它优化了代码吗?或者有什么可能的泄漏?
Is it a best practise to pass provider as an argument to widgets?
I am aware that we can directly access provider from within the widget.
But saw a couple of code snippets passing provider as an argument to child widget.
Does it optimize the code? Or any possible leaks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最好从需要它的小部件中访问提供程序,因为提供程序使用 BuildContext (如 Provider.of(context) 中)来获取 的实例所请求的提供的服务,基于小部件在小部件树中的位置,因为它遍历上面的层次结构来查找它。为了方便起见,您可以这样做,但是小部件应该足够封装和足够解耦,以便不依赖于更高层的小部件来获取数据,从而使它们自给自足和独立。我的两分钱。
It is better to access the provider from within the widget that requires it, since the Provider uses the BuildContext (as in Provider.of(context)) to fetch an instance of the requested provided service, based on the location of the widget in the widget tree as it traverses the hierarchy above to find it. You can do it for convenience, but widgets should be encapsulated enough and decoupled enough so as not to depend on higher above widgets to get data fed to them, making them self-sufficient and independent. My two cents.