SharedPreferences error in Flutter
Solution 1:
To debug this, use the following:
Future<SharedPreferences> _sprefs = SharedPreferences.getInstance();
_sprefs.then((prefs) {
// ...
},
onError: (error) {
print("SharedPreferences ERROR = $error");
});
In my case the error was that I wanted to call await SharedPreferences.getInstance()
before I called runApp()
, so that solution the error message gave me was to order my code as follows:
First:
WidgetsFlutterBinding.ensureInitialized();
Afterwards:
SharedPreferences prefs = await SharedPreferences.getInstance();
Finally:
runApp(...);
Solution 2:
I solved this using the following workaround:
Future<SharedPreferences> prefs = SharedPreferences.getInstance();
prefs.then(
(pref)
{
//call functions like pref.getInt(), etc. here
}
);