Search code examples
flutterdartsharedpreferences

Data isn't showen after fetchig it from sharedpreferences


I save data to sharedpreferences, but when I get the data, it isn't shown at the screen. I can print the correct data in the console log, but I am not able to show it on the screen.

This is the variable:

int oldDate = 0;

This is the code where I get the data from sharedprefs:

  Future<int> getDataIntTest() async {
    final prefs = await SharedPreferences.getInstance();
    oldDate = prefs.getInt("oldDate");
    setState(() {});
  }

And this is the place in my Scaffold where I want to print it to the screen:

 @override
  Widget build(BuildContext context) {
    oldDate = formattedDate;
    return Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            Text(
              oldDate.toString(),
            ),
          ],
        ),
      ),
    );
  }

In my point of view the setState should update the screen and than the new data should be displayed. The confusing thing is that I can print the correct data in the console log after fatching it, but displaying on the screen isn't possible.


Solution

  • I tried this, just remove the formattedDate

    class _MyHomePageState extends State<MyHomePage> {
      
       int oldDate = 0;
       Future<int> getDataIntTest() async {
         oldDate = 5;
         setState(() {});
       }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Column(
              children: <Widget>[
                InkWell(
                  onTap: (){
                    getDataIntTest();
                  },
                  child: Text(
                    oldDate.toString(),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    
    }