Mahmoud Ayyash
Mahmoud Ayyash

Reputation: 33

Why I did not get the latest data from Shared preferences when storing data from firebase background message?

I`m trying to store the newest data came from firebase notify while the app is in background or fully closed like this:

@pragma('vm:entry-point')
  static Future<void> _firebaseMessagingBackgroundHandler(
      RemoteMessage message) async {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp(
      name: 'taxigo',
      options: DefaultFirebaseOptions.currentPlatform,
    );
    SharedPreferences _sharedPref = await SharedPreferences.getInstance();
    _sharedPref.setString('testing', 'test1');
    print(_sharedPref.getString('testing'));
  }

It print test1 as expected. But inside main function, I`m trying to print the same thing using onMessageOpenedApp firebase function like this:

void main() async {
  await Firebase.initializeApp(
    name: 'taxigo',
    options: DefaultFirebaseOptions.currentPlatform,
  ).then((value) {
  });

  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
    SharedPreferences _sharedPref = await SharedPreferences.getInstance();
    print(_sharedPref.getString('testing'));
  });
}

but it prints null, but if i restart the app it will print test1. I noticed if I update the value of testing to test2 and restart the app, The onMessageOpenedApp will print the old value (test1).

I expect that onMessageOpenedApp function should print the latest value stored to shared preferences.

Upvotes: 0

Views: 31

Answers (1)

Mahmoud Ayyash
Mahmoud Ayyash

Reputation: 33

I solved the problem by adding .reload() function to onMessageOpenedApp like this:

FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async { await sharedPref.reload(); 
print(sharedPref.getString('testing')); 
});

Upvotes: 0

Related Questions