I’m trying to call async functions in my initstate and I succeed, the problem is that unlike what it normally does build is executed before initstate.
This is my code and of course it gives me an error because the late variables are not assigned before build:
late int oraNotifiche;
late int minutiNotifiche;
aggiornaImpostazioni() async {
final prefs = await SharedPreferences.getInstance();
await checkNotificheCalendario();
int timestap = await prefs.getInt("oraNotifiche") ??
DateTime(DateTime.now().year, DateTime.now().month,
DateTime.now().day - 1, 19, 0)
.millisecondsSinceEpoch;
DateTime orarioSalvato = DateTime.fromMillisecondsSinceEpoch(timestap);
oraNotifiche = orarioSalvato.hour;
minutiNotifiche = orarioSalvato.minute;
if (!mounted) return;
setState(() {});
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
await aggiornaImpostazioni();
});
}
2
Answers
create a future method like this
and call this method in the initState method without writing the await keyword
In this case, keep some default values for late variables as following.
Please avoid use late variable if you can’t initialise before the usage.