How to access Shared Preferences in FirebaseMessaging background and FirebaseMessaging.onMessage - flutter

I want to get values from Shared Preferences when I will receive anything in bakckground with FirebaseMessaging.onMessage.listen((RemoteMessage message) async {} .
I have tried to access it but it does not give any value from shared pref.
How to get it?

Force refresh in order to avoid empty instance of Shared Preferences.
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.reload();
final Int? soundVolume = prefs.getInt('sound_volume');
print(soundVolume);
});
Reference: https://pub.dev/documentation/shared_preferences/latest/shared_preferences/SharedPreferences/reload.html

Related

SetState and Shared Preferences returning null

I am having trouble identifying as to why setState() is returning null on my shared preferences getString method.
I am calling an async function outside of the initState and the constantly printing null when i check the return string of getString on page load.
I have checked that setString is saving the correct string to the key.
Here is my code:
void initState() {
super.initState();
retrieve();
}
retrieve() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
name = prefs.getString("displayName");
print(name);
});
}
Here is where I setString(in the register user page):
try {
UserCredential result =
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
);
final user = FirebaseAuth.instance.currentUser;
final name = _usernameController.text;
// if (user != null) {
await user?.updateDisplayName(name);
Navigator.pushNamed(context, homeRoute);
print(name);
You should set ,username via shared preference before accessing it.
final prefs = await SharedPreferences.getInstance();
In register page.(where you want to set name via SharedPreference before accessing it)
await prefs.setString('displayName', 'name');
After setting it in registeration you can access like above
name = prefs.getString("displayName");
When SharedPreferences return null value it means you have not set value with your key yet. So firstly set something like this:
final prefs = await SharedPreferences.getInstance().reload();
await prefs.setString('displayName', 'Mark');
then try to call it.
Thanks to all who have spent the time to respond to help. I hope this answer might help some one else down the track.
I found that Shared Preferences was not saving the data - my code was fine after all. I simply just closed the app and restarted the X code build from scratch and it is now working.....

how to retrieve a value from shared preferences instantly? - FLUTTER

I'm trying to show a page as an initial login, this is only displayed when my switch value is set to true.
The switch value is stored with shared preferences but when I open the application it is not recovered, only after an application update is it actually recovered. how can i get it to be recovered instantly when i open my application?
below the code:
Future<bool> saveSwitchState(bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("switched", value);
print('Switch Value saved $value');
return prefs.setBool("switched", value);
}
Future<bool> getSwitchState() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
SettingsPage.switched = prefs.getBool("switched")!;
print(SettingsPage.switched);
return SettingsPage.switched;
}
on another page then the value that is actually recovered:
if(AuthPage.authenticated == false && SettingsPage.switched == true ) {
yield ProfileNoAuth();
return; }
you can use dependency injection follow these steps :
get it package
create a Separate dart containing the following code file like this:
GetIt locator = GetIt.instance;
Future<void> setupLocator() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
locator.registerLazySingleton<SharedPreferences>(() => sharedPreferences);
}
call the setupLocator() method and wait for it in your main function
void main() async {
await setupLocator();
runApp(App());
}
access SharedPreferences Instance from anywhere like this:
locator();
now the SharedPreferences Instance if available anywhere in your project
please note that you dont have to wait for getting the Instance anymore, because you have only one Instance sharable across the application
bool getSwitchState() {
final prefs = locator<SharedPreferences>();
SettingsPage.switched = prefs.getBool("switched")!;
print(SettingsPage.switched);
return SettingsPage.switched;
}

How To save and load an Object using SharedPreferences

So I have been trying to load all of my Recent Search history object using shared preferences.
and it doesn't work, it says that "List is not a subtype of List" the error code happens when I call the loadData function. I don't know why my code is not working.
So this is my shared preferences and method code:
void _addLastSearch(String hospitalId,String hospitalName)
{
final lastSearching=SearchModel(hospitalId: hospitalId,hospitalName: hospitalName);
setState(() {
recentSearch.add(lastSearching);
});
}
void savedData() async {
SharedPreferences prefs= await SharedPreferences.getInstance();
prefs.setString('data',jsonEncode(recentSearch));
}
void loadData()async{
SharedPreferences prefs= await SharedPreferences.getInstance();
print("test masul load");
recentSearch=jsonDecode(prefs.getString('data'));
print(recentSearch.length);
}
any im changin the load data function to:
recentSearch=(jsonDecode(prefs.getString('data'))).map((item)=>SearchModel.fromJson(item)).toList();

SharedPreferences always null on Startup - Flutter

I've been trying to keep the user logged in if they haven't logged out, just simple SharedPreferences stuff, but every time that I save my SP and I hot reload, or hot restart my app, the function returns null, just like it didn't save anything. I've tried literally everything but can't figure it out. This is my code:
Getting my SPs on startup
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
isLoggedIn = prefs.getBool('isLoggedIn');
Timer(Duration(milliseconds: 100), ()=>{print(isLoggedIn)});
runApp(MyApp());
}
Saving my SPs after successful user login
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('isLoggedIn', true);
bool isLoggedIn = prefs.getBool('isLoggedIn');
print(isLoggedIn);
The writing functions on Shared Preferences are asynchronus sou you need to await them.
Try await prefs.setBool('isLoggedIn', true);

Save and Retrieve notification with shared preferences list flutter

I have implemented Firebase Cloud Messaging in my flutter application. Everything works well but I want to store all list of messages locally with shared preferences and retrieve them in another screen. All my logic does not work well as I can't save the messages when the onMessage function is called.
PushNotificationService
class PushNotificationService {
final FirebaseMessaging _fcm = FirebaseMessaging();
List<String> titles;
List<String> msgs;
Future initialise() async {
notiList = List<NotiMessage>();
if (Platform.isIOS) {
// request permissions if we're on android
_fcm.requestNotificationPermissions(IosNotificationSettings());
_fcm.configure();
// For testing purposes print the Firebase Messaging token
String token = await _fcm.getToken();
print("FirebaseMessaging token: $token");
} else{
String token = await _fcm.getToken();
print("FirebaseMessaging token: $token");
}
_fcm.configure(
// Called when the app is in the foreground and we receive a push notification
onMessage: (Map<String, dynamic> message) async {
print('onMessage: $message');
//add list of messages to shared preferences
_setMessage(message);
},
// Called when the app has been closed comlpetely and it's opened
// from the push notification.
onLaunch: (Map<String, dynamic> message) async {
print('onLaunch: $message');
_serialiseAndNavigate(message);
//add list of messages to shared preferences
_setMessage(message);
},
// Called when the app is in the background and it's opened
// from the push notification.
onResume: (Map<String, dynamic> message) async {
print('onResume: $message');
_serialiseAndNavigate(message);
//add list of messages to shared preferences
_setMessage(message);
},
);
}
void _serialiseAndNavigate(Map<String, dynamic> message) {
var notificationData = message['data'];
var view = notificationData['view'];
if (view != null) {
// Navigate to desired page
if (view == 'create_post') {
}
}
}
_setMessage(Map<String, dynamic> message) {
//add list of messages to shared preferences
final notification = message['notification'];
final data = message['data'];
final String title = notification['title'];
final String body = notification['body'];
String mMessage = data['message'];
//add to list
titles.add(title);
msgs.add(mMessage);
//save to shared preferences (does not work)
storeTitles(titles);
storeMsgs(msgs);
print("Title: $title, body: $body, message: $mMessage");
}
void storeTitles(List<String> list) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setStringList("notiTitles", list);
//list returns null
}
void storeMsgs(List<String> list) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setStringList("notiMsgs", list);
}
Future<List<String>> getTitles(List<String> list) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
list = prefs.getStringList("notiTitles");
return prefs.getStringList("notiTitles");
}
Future<List<String>> getMsgs(List<String> list) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
list = prefs.getStringList("notiMsgs");
return prefs.getStringList("notiMsgs");
}
}
Whats the best way to achieve this. I want to save the messages persistently and call them in another screen. Please help me.
The code on saving the List on shared_preferences seems to be ok. The issue might be on how the data is fetched. If you're storing critical data, I suggest to better use something like provider instead. The shared_preferences plugin is unable to guarantee that writes will be persisted to disk after returning as mentioned in its docs.