Home > Blockchain >  How to Save List in SharedPreferences in Flutter
How to Save List in SharedPreferences in Flutter

Time:07-28

Hello all at first I want to mention that I've tried a lot of solutions here but it didn't work for me.

I bring the list from the database through the following code:

 var listCat = [];
  Future getdata() async {
    apiURL = '***************.php';
    var response = await http.post(Uri.parse(apiURL));
    var responsebody = jsonDecode(response.body);
    if (responsebody.length >0){
      for (int i = 0; i < responsebody.length; i  ) {
        listCat.add(responsebody[i]['name']  ':'   responsebody[i]['image'].toString());
      }
      return responsebody;
    }else{
  

    }
  }

As is obvious in the code above I am trying to get the name and image and this is not a problem right now I want to store this listCat in SharedPreferences until I recall it from all pages of the app

I have the following class to save SharedPreferences:

class APIPreferences {
  static SharedPreferences ? _preferences;
  static const _keyMuinCat = 'MuinCat';



  static Future init() async => _preferences = await SharedPreferences.getInstance();


  static Future setMuinCat(String MuinCat) async => await _preferences!.setString(_keyMuinCat, MuinCat);



  static String? getMuinCat() => _preferences!.getString(_keyMuinCat);



}

Then I save what I need to save by the following line:

APIPreferences.setMuinCat(listCat.toString());

Then I can bring pre-stored data from any location where I need it through the following code:

CatList = APIPreferences.getMuinCat() ?? '';

I tried to do the following thing now to save the list in the first code above:

var listCat = [];
  Future getdata() async {
    apiURL = '***************.php';
    var response = await http.post(Uri.parse(apiURL));

    var responsebody = jsonDecode(response.body);

    if (responsebody.length >0){

      for (int i = 0; i < responsebody.length; i  ) {
        listCat.add(responsebody[i]['name']  ':'   responsebody[i]['image'].toString());
        APIPreferences.setMuinCat(listCat.toString());

      }

      return responsebody;
    }else{


    }
  }

But it didn't work. I don't really know how to deal with it.

How can I save it and then bring it to use with ListView.

CodePudding user response:

To save the list in shared preferences you need to pass as jsonEncode(yourList data) and when you will fecth the shared list you will again jsonDecode(your list)

await prefs.setString('YOUR KEY', json.encode(YOURMAP()));

CodePudding user response:

instead of:

_preferences!.setString(_keyMuinCat, "some string");

use:

_preferences!.setStringList(_keyMuinCat, ["some", "strings", "in", "list"]);

So in your code, the setMuinCat method needs to be:

static Future setMuinCat(List<String> muinCat) async => await _preferences!.setStringList(_keyMuinCat, muinCat);

and then you call it like this:

APIPreferences.setMuinCat(listCat);
  • Related