Ad

How To Save Prefs To Different Scopes In Flutter?

- 1 answer

I am trying to use shared prefs to store App Data and User Data differently, like this :

{
    "APP_DATA": {
        "banners": "{\"success\":true,\"data\":{}}",
        "gameList": "{\"success\":true,\"data\":{}}"
    },
    "USER_DATA": 
      {
          "emailVerified": "N",
          "userName": "97144554455",
          "playerToken": "W_8zUx3UCmFPeECjhhjhHhnnsajknHxAM0",
          "idVerified": "UPLOADED",
          "playerId": "412904",
          "bankList": "{\"84\":\"African Bank\",\"5\":\"FNB : First National Bank\"}",
          "unreadMsgCount": "0"
      }
}

But whenever I update any value in "APP_DATA" or "USER_DATA", it deletes the previous value and updates new value. Example : After adding "banners" and "gamesList" to my APP_DATA, I only see "gamesList" because it is overriding the "banners" value.

  MySharedPreferences.instance.setAppStringValue(
    "banners", jsonEncode(bannersModel),
  );

  MySharedPreferences.instance.setAppStringValue(
    "gamesList", jsonEncode(gamesListModel),
  );

This is the function I'm using

  setAppStringValue(String key, String value) async {
    SharedPreferences myPrefs = await SharedPreferences.getInstance();
    myPrefs.setString("APP_DATA", jsonEncode({key: value}));
  }

How to solve this issue?

Ad

Answer

What is happening is that you are overriding the APP_DATA key with a whole new value (encoded String) which results in the previous data to be lost.

If you want to keep the same structure, this is, having a key for APP_DATA and other for USER_DATA, both having their own data, you'll need to fetch the previous stored data and append the new one into it so you make sure you don't lose it.

 setAppStringValue(String key, String value) async {
    SharedPreferences myPrefs = await SharedPreferences.getInstance();

    final String storedData = myPrefs.get('APP_DATA');
    final Map newData = {key: value};

    try {
      // Has previous data, decode it and append into the new one
      if (storedData != null) {
        newData.addAll(jsonDecode(storedData));
      }
    } catch (ex) {
      print('Couldn\'t parse the stored data: $ex');
    }

    myPrefs.setString('APP_DATA', jsonEncode(newData));
  }
Ad
source: stackoverflow.com
Ad