Search code examples
fluttersharedpreferencessetstateflutter-widget

why doesn't flutter update the status of my widgets?


I am using the shared_preferences within my app to save some data but they only update the second time I open them


Solution

  • prefs.setInt is Future method, try putting await before all of it.

    async{
       final prefs = await SharedPreferences.getInstance ();
       
        ///others 
       await  prefs.setInt ('s$current month $current year', s);
       setState (() {  });
      }
    

    And create another method to fetch data on initState like

      fetchData()async{
        final prefs = await SharedPreferences.getInstance ();
        hours  = prefs.getInt(...);
       ///.... 
        setState(() {  });
      }
    
      @override
      void initState() {
         super.initState();
         fetchData();
      }