there are two ways to exit from our Android (Flutter) app, we can press back button repeatedly or we can just press home button
if a user press home button
(not back button), then the app will be in the background. and I send FCM (Firebase Cloud Messaging) push notification to users, and the app will receive the message in background handler. and then I save a string in the shared preference like this
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString("myKey", "value here");
final testValue = prefs.getString("myKey");
print("value in background handler: $testValue"); // I confirm I can get the saved value here
}
as you can see from the code above, I can get the value from the shared preference in firebaseMessagingBackgroundHandler
after receiving push notification, the user will open the app and it will directly open the home page.
In the home page, I try to get the value I saved before
@override
void initState() {
super.initState();
WidgetsBinding.instance?.addPostFrameCallback((_) async {
final prefs = await SharedPreferences.getInstance();
final savedValue = prefs.getString("myKey");
print(savedValue); // I get null here initially
});
}
as you can see, I get null value when I go back directly to the app. I have to exit the app again using back button
and then eventually I can get the string value from shared preference.
why I have to press back button to get the value from shared preference? how to solve this?