简体   繁体   English

Flutter 提供者最佳实践

[英]Flutter Provider best practice

I have been experimenting with the provider package and am usually able to get it to do what I want it to do.我一直在尝试提供者 package 并且通常能够让它做我想做的事情。 However, in some cases I am not sure if what I am doing is at all best practice.但是,在某些情况下,我不确定我所做的是否是最佳实践。

For example, suppose I have a settings page with various, unrelated options - say a theming option, a notifications option, some filter options specific to the app etc.例如,假设我有一个包含各种不相关选项的设置页面——比如主题选项、通知选项、特定于应用程序的一些过滤器选项等。

My question is, should each of these options have their own class dedicated to a single value so that only the parts of the widget tree dependent on that single value rebuild.我的问题是,这些选项中的每一个是否应该都有自己的 class 专用于单个值,以便只有依赖于该单个值重建的小部件树的部分。 Or should they all be in the same SettingsProvider class, and there is some way of using the fields in this class separately so as to avoid excessive rebuilds?还是它们都应该在同一个SettingsProvider class 中,并且有某种方法可以分别使用此 class 中的字段以避免过度重建?

Or am I missing the bigger picture entirely?还是我完全错过了大局? Any help would be great thanks!任何帮助都会非常感谢!

A solution I've found is to put all the values in a single class eg SettingsProvider .我发现的一个解决方案是将所有值放在一个 class 例如SettingsProvider中。 Then, instead of using Provider.of<> or Consumer<> ,然后,而不是使用Provider.of<>Consumer<>

use Selector<> .使用Selector<> For example, to get/set the notifications option of settings, you could wrap the widget with a Selector like so -例如,要获取/设置设置的通知选项,您可以使用Selector包装小部件,如下所示 -

Selector<SettingsProvider, bool>(
   builder: (context, notifications, child) {
      (notifications) 
      ? return Text('Notifications are on') 
      : return Text('Notifications are off')
   }, 
   selector: (context , settingsPro) => settingsPro.notifications,
),

This should display whether or not the notifications are on, and is only rebuilt when the notification option changes.这应该显示通知是否打开,并且仅在通知选项更改时重建。

Here is the provider doc page 这是提供者文档页面

Here is an article about Selector 这是一篇关于Selector的文章

Let me know if there are any better solutions.让我知道是否有更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM