Reputation: 4401
my flutter application checks for saved data in SharedPreferences
every time it starts . to use it later in the application, but when I run the app for the first time in a device, there is saved SharedPreferences
yet so it gets all the data as null
. so I want to make sure that it checks if the file itself exists rather than checking for a specific value,
note: I'm using this shared_preferences futter package.
here is my code :
checkingTheSavedData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String username = prefs.getString('username');
if (username == null) {
Navigator.pushReplacementNamed(context, '/login');
} else {
Navigator.pushReplacementNamed(context, '/main_page');
}
}
So, for the frist run it does Navigator.pushReplacementNamed(context, '/main_page');
but with empty data , after that when i do a real login and the data is already saved , it works fine. any idea how to handle this in a proper way ?
Upvotes: 10
Views: 15066
Reputation: 2633
Though already you got your answer, nevertheless here I mentioned how I used in my app.
Set the value using this
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("login", true);
Check by containsKey in Login page
SharedPreferences prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey("login")) {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) {
return LoginPage();
},
));
}
also check in logout page like this
SharedPreferences prefs = await SharedPreferences.getInstance();
if(prefs.containsKey("login")) {
prefs.remove("login");
Utils.successToast("Logout successfully");
Navigator.of(context).pop();
}
Note : you can use whatever you want like 'username' or something else instead on "login"
Upvotes: 3
Reputation: 573
When I use "shared_preferences", I personally use an helper to get and set just like this :
GETTER
static Future<String> getUserName() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('username') ?? '';
}
SETTER
static Future<String> setUserName(String value) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.setString('username', value);
}
To answer your question, you can't check if the SharedPreferences "file" exist or not. Your method is already correct.
Upvotes: 8
Reputation: 7563
You need to check if the key exists yet by using prefs.containsKey('username')
.
Upvotes: 21
Reputation: 61
You are getting empty because you do not have your SharedPreferences KEY yet;
so just put ??
operator and return a value.
// Separated shared preferences method is a good call
Future<bool> isUserLoggedIn() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool(IS_LOGGED_KEY) ?? false;
}
// Your logic
void checkingTheSavedData() {
isUserLoggedIn().then((isLogged) {
if (isLogged) {
// foo
} else {
// bar
}
});
}
Upvotes: 4