This is my controller.dart file which checks if users is verified or not and then return the page according to the conditions.
My question is that why the build widget is executing first before initState()
? I tried to debug this code using breakpoints and noticed that build() widget
is running first and then the initState()
Why this is happening and how could I fix it ?
This is my code :
class _ControllerState extends State<Controller> {
late bool auth;
@override
Widget build(BuildContext context) {
return (auth==false) ? Onbording() : IndexPage();
}
@override
void initState() {
super.initState();
WidgetsBinding.instance!.addPostFrameCallback((_) async {
await this.checked_if_logged();
});
}
Future<void> checked_if_logged() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if(prefs.getBool('verified')==true){
setState(() {
auth = true;
});
}else{
setState(() {
auth = false;
});
}
}
}
This is a snapshot of my debug code where the blue line is showing that it runs first before init and because the bool auth
is a late
type so it throws lateInitializationErrror
and after that initState() is called which initializes the auth
variable which rebuild the widget and removes the error
Update:
I noticed that when I replace the WidgetsBinding.instance!.addPostFrameCallback((_)
with just check_if_logged()
, the initState()
is calling first but before completion of check_if_logged()
the build widget executes first which again throws lateInitializationError