skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search