Flutter: Using SharedPreferences in Flutter and native
Been experimenting with Flutter recently and had a use case where I wanted to access SharedPrefernces in Flutter and in native. Surprisingly it was a bit tricky and took a bit of digging.
To use SharedPreferences in Flutter the
shared_preferences package is required and you use them like this:
SharedPreferences prefs = await SharedPreferences.getInstance(); var prefsStartTime = prefs.getString('startTime');
In Java, you’d do it like this:
SharedPreferences sharedPref = context.getSharedPreferences("", Context.MODE_PRIVATE); String startTime = sharedPref.getString("startTime", "");
However, due to the way that the Flutter plugin is implemented this doesn’t give you the same value.
First, from here we can see that the
SHARED_PREFERENCES_NAME is set to
FlutterSharedPreferences. So, to access the same set of preferences we must use the same name.
SharedPreferences sharedPref = context.getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE);
Secondly, the name of the preference itself, in this case
startTime, is also incorrect.
Looking at this we can see that the plugin prepends
flutter. to all the preference names. So, the correct way to access the preference is:
String startTime = sharedPref.getString("flutter.startTime", "");
And that finally allows us to read preferences in Flutter and Java consistently.
Hope this saves someone some Googling and source-code reading.
Get in touch
Or send me feedback. It will take less than 20 seconds.