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 ?
You need to check if the key exists yet by using prefs.containsKey('username')
.