I am using
shared_preferences: ^2.0.15
and save my values in local.
But when i change my screen and get my values app give me error be like this.
My question "How can i initialize SharedPreferences in best way?".
late SharedPreferences _preferences;
@override
void initState() {
super.initState();
getLocalData();
}
Future getLocalData() async {
_preferences = await SharedPreferences.getInstance();
}
CodePudding user response:
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 :)
CodePudding user response:
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 protected]");
}
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