This is my simple ChangeNotifier:
class Settings extends ChangeNotifier{
void changedSettings(){
notifyListeners();
}
}
I have this in my build method:
Provider.of<Settings>(context);
and the widget rebuilds as expected when I call a function that calls notifyListeners in Settings. However, I only want to run an expensive data reload if the rebuild was because of the Provider, and not because some other Flutter management reason.
My ideal solution to this is I can register some sort of callback function when I register the Provider.of in my build method...for example:
Provider.of<Settings>(context).withCallback(this._getData(this.state_settings));
Instead, what I am doing now is:
class Settings extends ChangeNotifier{
late int lastChange;
Settings(this.lastChange);
void changedSettings(){
lastChange = DateTime.now().microsecondsSinceEpoch;
notifyListeners();
}
}
...
int lastChange = Provider.of<Settings>(context).lastChange;
if(lastChange != lastSettingsChange){
lastSettingsChange = lastChange;
_getDataFuture = getData();
}
CodePudding user response:
Irrespective of what triggered a rebuild, the choice to do/not do an "expensive data reload" must be managed differently. For example, you should be setting a state (that you listen to) which directs your build to do a data reload or not, based on that state.
This is how we use reactive programming and state management. The "state" must not be concerned with the "actions" taken on that state - the typical examples are the "loading", "loaded" and "error" states on performing a network read/write.
CodePudding user response:
In the initState you can register a listener to this provider like Provider.of<T>(context,listen:false).addListener and this callback will be called whenever you do a notifyListener.
Or you can create your own listeners e.g look at the addStatusListener on the Animation class.
Also, if you have Provider.of<Settings>(context); in your build that means you are depending on it so the didChangeDependencies will be called when the Provider is notified.
