Bill Rei
Bill Rei

Reputation: 443

Flutter : How to use SharedPreference to get List<String>?

I've create an initState in my page and call callData to get favId (type : List) every I open this page. But, when the application start, my compiler show this error message :

_TypeError (type 'List<String>' is not a subtype of type 'String')

and this is my getData's function :

getData(favId) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    return pref.getStringList(favId);
  }

also this is my saveData's function :

void saveData() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setStringList("id", favId);
  }

How to fix this problem and I can call getData every I open this page in my application? Thank you :)

Upvotes: 0

Views: 529

Answers (2)

Alvin Chung
Alvin Chung

Reputation: 324

"id" is a String, you need to store a List<String> into setStringList

There are the steps if you want to add an item to the list:

List<String> ids = await getData(favId);
ids.add("id");
saveData(ids, favId);

then change the saveData() to

void saveData(ids, favId) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setStringList(ids, favId);
}

getData()

List<String> getData(favId) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    return pref.getStringList(favId);
}

Upvotes: 1

Ranjit Shrestha
Ranjit Shrestha

Reputation: 762

if you want to save and retrieve List to and from SharedPreferences, you to use same key to save and retrieve the value.

here is a simple example,

const favKey = 'favoriteKey';

To save data,

void saveData(String favKey, List<String> favorites) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setStringList(favKey,favorites);
  }

To retrive data,

getData(String favKey) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    return pref.getStringList(favKey);
  }

Note: You need to use same key to set and get data using SharedPreference.

Upvotes: 1

Related Questions