Question: I'm facing an issue with my Flutter app where Firebase data doesn't update when the app is reopened from a terminated state (e.g., closed from the recent apps list). Here's a brief description of the problem and what I've tried:
Problem:
I'm using Firebase Realtime Database and shared preference to store and retrieve data in my Flutter app. When user open app for first time it read data from firebase and store in shared preference, later the value will be take from shared preference(i do it for reducing the data reading times)
await refOrg.onValue.first.then((event) {
// log('event$event');
for (final child in event.snapshot.children) {
var newsKey = child.key ?? 'Key not found';
log(newsKey.toString());
var newsValue = child.value;
log(newsValue.toString());
sharedPreferences.setString(newsKey, newsValue.toString());
var prefGet = sharedPreferences.getString(newsKey.toString());
log("save value= ${prefGet.toString()}");
}
When the app is running in the foreground or background, Firebase data updates are received and processed correctly. i.e, it gets the data and update the shared preference with new value
refOrg.onChildChanged.listen((event) {
DataSnapshot snapshot = event.snapshot;
String key = snapshot.key ?? 'no key';
log(key.toString());
dynamic value = snapshot.value;
sharedPreferences.setString(key, value);
var prefGet = sharedPreferences.getString(key);
// if (key == 'version') {
// version = value;
// log('value:$value');
// }
log("save value= ${prefGet.toString()}");
log('Key: $key, Value: $value');
});
However, when I fully terminate the app (close it from the recent apps list) and then reopen it, the app doesn't seem to fetch the updated data from Firebase
When I searched on internet about this issue resulted as, Foreground and Background Sync: When the app is in the foreground or background (not fully terminated), Firebase can synchronize data in real-time, and listeners like onChildChanged should work as expected.
Terminated App: When the app is fully terminated (closed from the recent apps list), Firebase synchronization is paused, and the app won't receive real-time updates until it's opened again.
Help: What could be causing this issue, and how can I ensure that my Flutter app fetches the latest Firebase data when it's reopened from a terminated state?