How to store data as array in getStringList(Shared Preference) in Flutter

953 Views Asked by At

I am trying to store the array of documentId when the user click's on the screen. I tried to write and load the data using SharedPreference but it is stored as a string, not as an array.

MyCode:

_writedata() async{
      final prefs = await SharedPreferences.getInstance();
      final key = 'my_key';
      prefs.setStringList(key, [docId]);
    }

_loadData() async{
      final prefs = await SharedPreferences.getInstance();
      final key = 'my_key';
      final value = prefs.getStringList(key) ?? [];
      print('load data: $value');
    }

My output:

I/flutter (17292): load data: [9koh2fe2T4FydH2xoqzo]
I/flutter (17292): load data: [aV58m2nZsHtCtGafidh2]
I/flutter (17292): load data: [60Q9uduXR5sqMww1i58D]
I/flutter (17292): load data: [EmrgSlHOGDUHqzDFo4vm]
I/flutter (17292): load data: [D5mJi5Tt6p8GKP9OyE8r]

Can someone please guide me on how to store this in the array format by avoiding duplicate values?

Thanks for your time.

1

There are 1 best solutions below

0
On BEST ANSWER

I think you are mistaken about what setStringList does. All it does is saving the list you give to it. It does not add to an existing list, or check contents of the lists.

If you want a specific logic, like adding to the list or removing duplicates, you need to get the list, manipulate the list as you see fit and then set this list.