I have this function:
Future<String> load(SharedPreferences prefs, String fileName) async {
prefs = await SharedPreferences.getInstance();
String jsonString = prefs.getString(fileName) ?? "";
if (jsonString.isNotEmpty) {
return jsonString;
}else{
return ...
}
}
What should I return in the else case? I tried with "" but it doesn't work.
Shared Preferences
In Flutter, Shared Preferences are used to store primitive data (
int
,double
,bool
,string
, andstringList
). This data is associated with the app, so when the user uninstalls your app, the data will also be deleted.Get the plugin
The shared_preferences plugin from pub is a wrapper around Android
SharedPreferences
and iOSNSUserDefaults
. You can get this plugin by adding theshared_preferences
line to your pubspec.yaml file in the dependencies section.Change the version number to whatever the current one is.
Import the package
In whichever file you need the Shared Preferences, add the following import:
Reading and writing data
To get the shared preferences object you can do the following:
This will be used for all of the following examples.
int
final myInt = prefs.getInt('my_int_key') ?? 0;
prefs.setInt('my_int_key', 42);
double
final myDouble = prefs.getDouble('my_double_key') ?? 0.0;
prefs.setDouble('my_double_key', 3.14);
bool
final myBool = prefs.getBool('my_bool_key') ?? false;
prefs.setBool('my_bool_key', true);
string
final myString = prefs.getString('my_string_key') ?? '';
prefs.setString('my_string_key', 'hello');
stringList
final myStringList = prefs.getStringList('my_string_list_key') ?? [];
prefs.setStringList('my_string_list_key', ['horse', 'cow', 'sheep']);
See also
The answer is "it depends". Namely, it depends on what exactly you are doing with the result of this function, and what a good empty default value means in that context.
Assuming you're decoding the returned JSON string into a
Map<String, dynamic>
, then a good default value might be the empty map. In that case, you could reformulate your function as follows:However, it probably makes more sense to reformulate this procedure as a slightly higher-level function returning actual map values: