简体   繁体   中英

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. 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. 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?

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 . Then, instead of using Provider.of<> or Consumer<> ,

use Selector<> . For example, to get/set the notifications option of settings, you could wrap the widget with a Selector like so -

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

Let me know if there are any better solutions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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