I have a problem with inconsistent shared preferences value. I will try to describe it as simple as possible.
I'm using Firebase Cloud Messaging for push notifications. When app is in background and notification came in, background handler bellow is invoked.
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final int counter = (prefs.getInt('badge') ?? 0) + 1;
prefs.setInt('badge', counter).then((bool success) {
print(counter);
});
}
My widget uses WidgetsBindingObserver to determine lifecycle state. When I enter the app, state of that widget is onResume and there I want to read that badge value from shared preferences like this.
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final int counter = (prefs.getInt('badge') ?? 0);
print(counter);
}
}
Scenario 1:
- App opened, notification came in - set badge field to 1.
- App in background, notification came in - background handler set badge field to 2.
- App resumed, read that badge field, it's still 1.
Scenario 2:
- App opened, notification came in - set badge field to 1.
- App in background, notification came in - background handler set badge field to 2.
- App in background, notification came in - background handler set badge field to 3.
- App resumed, read that badge field, it's still 1.
Question: Any idea why field isn't updated?