such as: in my app, i need to request some configs from server(maybe several apis), but this function(which combined these apis, but these child functions are in different providers/states) should be called exactly only once. so what's the correct way to do with it? because of build and didChangeDependencies function may called multi times, so i can't call init in these function, but in initState, the 'listen' parameter can only be 'false' and this will throw exception if i call multi different child function.
Examle:
i have A,B states
in A:
class AStates with ChangeNotifier {
...
appInit() async{
...
childInitFunc1();
childInitFunc2();
childInitFunc3();
// if i call initB it will throw exception whatever listen is true or false
Provider.of
}
...
}
in B:
class BStates with ChangeNotifier {
...
initB() async{
...
}
...
}
in index.dart:
class Test extends StatefulWidget {
@override
_TestState createState() => _TestState();
}
class _TestState extends State
@override
void initState() {
//
// init here and if listen is true, it will throw exception
//
Provider.of
WidgetsBinding.instance.addObserver(this);
super.initState();
}
@override
void didChangeDependencies() {
// can't init here
super.didChangeDependencies();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
Provider.of
super.didChangeAppLifecycleState(state);
}
@override
Widget build(BuildContext context) {
// can't init here
return Container();
}
}
so what's wrong with my code? and what should i do correctly ?
use Future.delay in initState like this https://github.com/rrousselGit/provider/issues/61
I tried an succeeded
@datvtwkm no.
There's a reason for these exceptions, and while sometimes using a Future this way may be the solution, that is not always the case.
@guopeng1994 widgets lifecycles can't be used to modify a provided value.
The value returned by Provider.of is supposed to be immutable.
If there's something to initialize, it should be done directly on the constructor of your model.
@rrousselGit thanks! i'll try that, hope this going to be work.
Closing it since it is answered.