I'm building a little pomodoro app with Flutter. I'm using the package shared_preferences to store a String and a Int.

Everything is working fine (loading and saving), but I'm trying to automatically change the displaying of the Int value with SetState, which doesn't work. The displaying value only change when I reload the app.

My saving method is :

_savePomo() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
  prefs.setInt('pomodoro', pomodoro);
});
}

The method is called everytime the podomoro finish a cycle. Before calling the method I increment the pomodoro variable =+1. I'm showing the value like this :

Text("It's your " + _pomodoro.toString() +"th pomodoro !");

Everything is happening in a stateful widget.


Solution 1: Gazihan Alankus

Where you do this:

_pomodoro += 1;

Convert it into this:

setState(() {
  _pomodoro += 1;
});

You also do not need to place the prefs.setInt in setState.


Solution 2: Dhaval Patel

You can try below code:-

int pomodoro = 0;
_savePomo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt('pomodoro', pomodoro);
    pomodoro = await prefs.getInt('pomodoro');
}

You can use pomodoro variable in Text widget like below:-

Text("It's your " + pomodoro.toString() +"th pomodoro !");