SharedPreferences always null on Startup - Flutter - 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);

Related

How to initialize SharedPreferences 2.0.15 in flutter? (Dart - Flutter)

I am using shared_preferences: ^2.0.15 and saving my values locally.
When I change my screen and get my values, I get an error.
How can I initialize SharedPreferences correctly?
Video
late SharedPreferences _preferences;
#override
void initState() {
super.initState();
getLocalData();
}
Future getLocalData() async {
_preferences = await SharedPreferences.getInstance();
}
I've checked the video you shared.
You're just missing to call the getLocalData method inside the LoginViewModel.
I'd suggest adding a line inside your loginRequest method to call getLocalData method. Well, don't forget to await.
await getLocalData();
That's it :)
actually you are not fetching data from your shared preference
you have to get the data that u saved
first set data that you want to save
addStringToSF() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('email', "email#email.com");
}
then in your second screen you can get your data
late SharedPreferences _preferences;
late String email;
#override
void initState() {
super.initState();
getLocalData();
}
Future getLocalData() async {
_preferences = await SharedPreferences.getInstance();
// for exemple you saved a string value with key ='email'
email= _preferences.getString('email');
}
check this : https://medium.flutterdevs.com/using-sharedpreferences-in-flutter-251755f07127

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

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

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;
}

Flutter SharedPreferences value to Provider on applcation start

I'm trying to to set a value from sharedpreferences to provider at application start.
this what I have so far, sharedpreferences to widget is working:
https://gist.github.com/andraskende/a19c806aeef0ce88e9a9cafa49660ab4#file-main-dart-L211-L223
Finally i figured out with trial and error... It can be done in the constructor as:
class BarcodeProvider with ChangeNotifier {
BarcodeProvider() {
setup();
}
void setup() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String url = (await prefs.getString('url') ?? '');
_url = url;
notifyListeners();
}
......
}
// global variable, that can be accessed from anywhere
SharedPreferences sharedPrefs;
void main() async { // make it async
WidgetsFlutterBinding.ensureInitialized(); // mandatory when awaiting on main
sharedPrefs = await SharedPreferences.getInstance(); // get the prefs
// do whatever you need to do with it
runApp(MyApp()); // rest of your app code
}

can't delete key from shared preferences.string list

so newbie question but i think i have done everything in accordance with the documentation and i can't find the bug i have List string with shared preferences and 3 function laod save delete ,load and save work perfect but delete doing nothing without errors :/
List favorites=[];
#override
void initState(){
super.initState();
setState(() {
_loadList();
});}
_loadList() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
favorites = (prefs.getStringList('myFavorites') ?? []);
});
}
_saveList(documentID) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setStringList('myFavorites', ['$documentID']);
_loadList();
}
_deleteList(documentID) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var list= prefs.getStringList('myFavorites');
list.remove(documentID);
_loadList();}
I couldn't find too many questions about it, I think my own stupidity forgets something. can someone help ?
I made a new list and add all keys to new list. deleted documentId in my new list and put the new list in place of myFavorites. Also works.