I have this code in _MyAppState in my main.dart :
var _p3provider;
@override
void initState() {
super.initState();
P3provider p3provider = new P3provider();
authentification(p3provider);
_p3provider = p3provider;
}
I pass the variable _p3provider as p3provider to MyHomePage statefulWidget of my main.dart,
Here is some code of _MyHomePageState :
void initState() {
super.initState();
if (widget.p3provider.jsession_id == null) {
Future.delayed(Duration(seconds: 2), (){
getTasks();
});
} else {
getTasks();
}
}
To execute my getTasks function I need the jsession_id variable from p3provider object to be initialized. This variable is initialized in the initState of _MyAppState at this line : authentification(p3provider); .
The problem is that both the initState of _MyAppState and _MyHomePageState are executed at the same time so if I directly call getTasks() in the initState of _MyHomePageState it will return an error because p3provider.jsession_id will not have been initialized yet.
To avoid this error I used a Future.delayed after a checking if the variable is null, but I don't think this solution is optimal, I would like the function getTasks() to be executed directly when jsession_id become not null.
If anyone has an idea on how to do this, you are more than welcome ! :)
CodePudding user response:
Found a solution :
I define this class :
class HomePageController{
var getTasks;
}
Which I instanciate in _MyAppState :
final HomePageController myController = HomePageController();
I pass it down to MyHomePage widget :
home: MyHomePage(controller: myController),
And in the initState of _MyHomePageState I assign my function getTasks() to the controller variable getTasks :
@override
void initState() {
super.initState();
widget.controller.getTasks = getTasks;
}
Now I can execute getTasks via the controller in _MyAppState :
@override
void initState(){
super.initState();
authentification().then((value){
myController.getTasks();
}
Here is the topic where I got it : Flutter calling child class function from parent class