I have notification details in SharedPreferences
as List<Notifications>
. I want to get the length of the list in real-time and update the UI.
Here is the code that I tried:
Future countNotifications() async {
final prefs = await SharedPreferences.getInstance();
final notificationsString = prefs.getString('notifications');
List<Notifications>? notifications;
// Decode the JSON string if it exists
if (notificationsString != null) {
notifications = (jsonDecode(notificationsString) as List)
.map((e) => Notifications.fromJson(e))
.toList();
}
return notifications!.length;
}
I know this function does not give real-time data. How to make it receive data in real-time.
4
Answers
Please stop reconstructing the instance of SharedPreferences all over your code. Initialize it once:
And now every get is synchronous:
It’s the "set" actions that are still async. But get is sync!
Certainly! To fetch
SharedPreferences
values in real-time in Android, you can useLiveData
. Here’s a concise example:And in your activity or fragment:
This example uses a
PreferenceManager
class withLiveData
to observe and react to changes inSharedPreferences
values in real-time.There is no live-update in shared_preferences. So there are several way to achieve what you want.
You can use one of the packages, which provide such functionality: streaming_shared_preferences or rx_shared_preferences. Both are streamed wrappers for classic shared preferences.
You can write your own wrapper for shared preference, which will notify on each change in your shared prefs (like in the packages above). The main idea is to create notification of changes when you save value and then to listen to the changes (you can see examples in the source code of the above packages).
You can use some other solution, which has streams/live-update like hive instead of shared preferences to store your data locally.
Certainly! To fetch SharedPreferences values in real-time in Android, use
SharedPreferences.OnSharedPreferenceChangeListener
. Here’s a concise example:Replace "your_pref_name" with your SharedPreferences file name and "your_key" with the key you want to observe. This example captures changes in real-time through the
onSharedPreferenceChanged
method.