Reputation: 1164
My flutter app is listening to SMS in foreground as well as background using the telephony package. While registering to receive the messages, I have used two methods (one for foreground and one for background, as required by the telephony package like this:
telephony.listenIncomingSms(onNewMessage: onMessage, onBackgroundMessage: onBackgroundMessage);
But inside both the methods have a call to a common method that saves the most recent SMS received to shared preferences, like this:
onMessage(SmsMessage message) async {
...
saveLastMsg(message);
}
onBackgroundMessage(SmsMessage message) async {
...
saveLastMsg(message);
}
saveLastMsg(SmsMessage message) async{
SharedPreferences sp = await SharedPreferences.getInstance();
sp.setString("lastsmsbody", message.body??'');
}
In App UI, I fetch the lastsmsbody like this:
SharedPreferences sp = await SharedPreferences.getInstance();
String body = sp.getString("lastsmsbody")??'';
I display this value in the UI. This is working fine when the App is running in the foreground. The data on the screen is updated as and when messages come in.
The problem is when the app is pushed in the background. From the logs, I see that it still receives the message and it still saves it in the preferences. But when I bring the app back to the foreground, it is not able to fetch that most recent message that was saved when the app was in bg. sp.getString("lastsmsbody") gets the old message that was saved when the app was in foreground.
I thought that may be preferences are different when app is in fg and bg. But if I kill the app and restart, sp.getString("lastsmsbody") returns the most recent message correct that was saved when the app was in bg.
Can someone tell me what is going on here?
Upvotes: 4
Views: 3098
Reputation: 21
Everytime my app is restarted, it always gets the old value for the 1st time, then new value if read again. reload() is NOT working. My solution is to call await prefs.remove('key') before updating with new value (e.g. prefs.setInt('key')),
await prefs.remove('key'); await prefs.setInt('key',100);
Upvotes: 2
Reputation: 53
I'm using a flutter_background_service dependency to do some task and because of that I'm not getting the updated value of my shared_preference variables. I just reload the shared_preference instance and it work's great for me. Like below:
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
Upvotes: 3
Reputation: 541
You may need SharedPreferences.reload
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
Upvotes: 11