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?
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>toSet<WordPair>ininitState? 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With