Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from Set to List in Dart / Flutter?

I have a Set of type Set<WordPair> & I want to convert it to List of type List<String> because I want to save it using SharedPreferences API in Flutter

Currently, my state looks like

final Set<WordPair> _saved = Set<WordPair>();

Now I want to save the _saved variable into SharedPreferences

If I do, prefs.setStringList('saved', _saved.toList()); it gives me compilation error like

[dart] The argument type 'Set' can't be assigned to the parameter type 'List'. [argument_type_not_assignable]

How do I store complete _saved variable in SharedPreferences?

like image 390
deadcoder0904 Avatar asked Sep 11 '25 09:09

deadcoder0904


1 Answers

The reason you are unable to save it in the Preferences even after converting it into a list is that you are trying to save StringList (prefs.setStringList) whereas your set is of type WordPair

A workaround for that could be,

prefs.setStringList('saved', _saved.map((WordPair wordPairItem) => wordPairItem.toString()).toList());

i.e converting each item into String and then save it as StringList

To your follow-up question in the comments:

how do I convert from List<String> to Set<WordPair> in initState? As there is no .toWordPair() & wrapping up takes 2 args so Idk how to do it?

As per documentation, WordPair is Representation of a combination of 2 words, first and second. Therefore, you can break the String into two substrings and pass those 2 substrings in the respective argument positions.

[Update] (solution proposed by the Author of the follow-up question) The solution can be found at here

like image 73
Daksh Gargas Avatar answered Sep 13 '25 07:09

Daksh Gargas