Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: shared preferences

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.

like image 896
Little Monkey Avatar asked Oct 16 '18 08:10

Little Monkey


1 Answers

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:

Future<String> loadJSON(final String fileName) async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  final String jsonString = prefs.getString(fileName);
  if (jsonString != null && jsonString.isNotEmpty) {
    return jsonString;
  }
  return "{}"; // default value
}

final String jsonString = await loadJSON("test.json");

final Map<String, dynamic> jsonData = json.decode(jsonString);

However, it probably makes more sense to reformulate this procedure as a slightly higher-level function returning actual map values:

Future<Map<String, dynamic>> loadData(final String fileName) async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  final String jsonString = prefs.getString(fileName);
  if (jsonString != null && jsonString.isNotEmpty) {
    return json.decode(jsonString);
  }
  return Map(); // default value
}

final Map<String, dynamic> jsonData = await loadData("test.json");
like image 184
Arto Bendiken Avatar answered Oct 23 '22 13:10

Arto Bendiken