I want to start a function that returns a future when MyChangeNotifier is changed.
Using a future builder widget and calling the function directly can work but this will also call the function when the widget is rebuilt, resulting in unnecessary calls to my function. The function should be called outside the build method like the init function but be called only when MyChangeNotifier is updated.
I did not find a solution to this problem.
In the init function, there is no build context to access MyChangeNotifier and add a listener. it seems that to access this build context you need to be in the build method that then forces you to be called each time the widget rebuilds.
What do I miss? Do you have an elegant solution to this problem?
I hope this speedo code helps you better understand my issue.
MyChangeNotifier extends ChangeNotifier {
//contains a list of directories that can be updated from anywhere in the app
}
MyWidget extend StatelessWidget { // probably some states are needed
Widget build(BuildContext context) {
var myChangeNotifier = Provider.of<MyChangeNotifier>(context);
return FutureBuilder(future: _computemd5(myChangeNotifier), builder: return Text(futur_result);); // the future is computed every time the build method is called not only when MyChangeNotifier changed.
}
future<String> _computemd5(MyChangeNotifier myChangeNotifier) {
// compute
}
}
2
Answers
The most elegant solution would involve using an external package with a relatively high learning curve- Riverpod.
Riverpod is a more robust version of Provider that allows you to have persistant asynchronous functions across your entire app scope.
From their website, the motivation for Riverpod is partially to answer your exact question:
To actually solve your problem, use an AsyncNotifierProvider as follows:
note: this uses the Riverpod code generator so you must
The build method (the function you want to call) will execute whenever the result changes.
When you need the result of the function in your code, simply watch the provider and handle loading and error states:
You can use a combination of
StatefulWidget
andListenableBuilder
. Ensure your widget is aStatefulWidget
since you need to manage state and lifecycle methods. Then, use aListenableBuilder
to listen to changes inMyChangeNotifier
. This widget will rebuild only when the notifier notifies its listeners, which is exactly what you need.