Flutter: shared preferences

后端 未结 2 595
后悔当初
后悔当初 2021-02-08 10:23

I have this function:

  Future load(SharedPreferences prefs, String fileName) async {
    prefs = await SharedPreferences.getInstance();
    String         


        
2条回答
  •  盖世英雄少女心
    2021-02-08 11:17

    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, then a good default value might be the empty map. In that case, you could reformulate your function as follows:

    Future 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 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> 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 jsonData = await loadData("test.json");
    

提交回复
热议问题