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 ?
To check if a key or record is present in shared preferences we have to use containsKey() method. This methods takes key as value and checks if the key is present in sharedpreferences. If the key is present it will return true else it will return false.
These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android. content. Context) with a context in the same package as this activity.
Click on the package name for your application. After that click on the shared_prefs folder and inside that open the shared_prefs. xml file. Now you will get to see the data which we stored in our shared preferences from our application.
Android Shared Preferences Overview Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.
You need to check if the key exists yet by using prefs.containsKey('username')
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With