-1

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();
    });
  }
Jonathan
  • 106
  • 1
  • 8

2 Answers2

0

create a future method like this

Future<void> yourDataLoadingMethod()async{
      /// your future call
    }

and call this method in the initState method without writing the await keyword

Munsif Ali
  • 1,839
  • 1
  • 8
  • 22
0

In this case, keep some default values for late variables as following.

 int oraNotifiche = 0;
 int minutiNotifiche = 0;

Please avoid use late variable if you can't initialise before the usage.

Alex Sunder Singh
  • 2,378
  • 1
  • 7
  • 17