Reputation: 1321
I have a mobile game which saves max score value after the game is finished and in the main page I display that max score. Because I load shared preferences data in main page initState()
function, unless user closes and reopens the app the max score does not change on the main page. Any solution ideas ?
this is play_game.dart file where I save results to sharedpreferences when user finishes the game:
Future saveResults() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
int maxSoz = int.parse(preferences.getString('max_soz'));
int maxPoint = int.parse(preferences.getString('max_xal'));
if (speed > maxPoint && soz > maxSoz) {
preferences.setString('max_xal', speed.toString());
preferences.setString('max_soz', soz.toString());
}
}
and this is the landing_page.dart where I display the max scores. I have a function to load sharedpreferences data:
Future loadData() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
this.maxSoz = preferences.getString('max_soz') ?? '0';
this.maxPoint = preferences.getString('max_xal') ?? '0';
});
}
and to load data, I mention that function in initState():
@override
void initState() {
super.initState();
loadData();
}
initState()
loades data (executes loadData()
function) when page is initialized first time. If gamer, after finishing the game, comes back to landing page from play_game page by clicking to "go back" button, the new max scores are not being shown on landing page because, as you may guess, function loadData()
only gets executed when page initalized (by initState()
).
Upvotes: 0
Views: 1358
Reputation: 1610
You could add await
in front of your Navigator
, for example:
...
...
final exit = await Navigator.of(context).pushNamed("/pages/play_game");
if (exit == true) {
loadData();
}
...
...
Notes: I am assuming that your
play_game.dart
will return something, for examplebool
Upvotes: 1