0
votes

I have created a bool List:

List<bool> switchbool = [true, true, true, true];

On change of a switch, the value change (pretty obvious...). But i would like to store those information exacltly as they are in the List, because i use them like this:

Switch(
       value: switchbool[index],
       onChanged: (value) {
       _saveBoolFromSharedPref(value, app[index]);
       setState(() {
    switchbool[index] = value;
    });
 },

)

But with this it doesn't load the true or false stored in the sharedPreferences that i saved...

Future<void> _getBoolFromSharedPref() async {
final prefs = await SharedPreferences.getInstance();
switchbool.length = app.length;
for (var i = 0; i < app.length; i += 1) {
  final myBool = prefs.getBool(app[i]) ?? false;
}

} and here is the _saveBoolFromSharedPref

Future<bool> _saveBoolFromSharedPref(bool value, String appName) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(appName, value);
//print(switchbool);

}

Any advices will be wonderful, thanks a lot! If I could maybe retreeive the data from the value field on the switch with a future void but i haven't seen anywhere any answer...

2
Can you add your _saveBoolFromSharedPref method too please? - Josteve
@zeus it should be ok? - Malopieds
Check my answer @Malopieds. - Josteve

2 Answers

1
votes

Maybe store your values in a map and then decode/encode them. Like following:

var jsn = prefs.getString('Map');
Map = json.decode(jsn);


 var jsn = json.encode(Map);
 prefs.setString('Map', jsn);

Let me know if it helps.

0
votes

Try this for your _getBoolFromSharedPref method.

Future<void> _getBoolFromSharedPref() async {
final prefs = await SharedPreferences.getInstance();
switchbool.length = app.length;
for (var i = 0; i < app.length; i += 1) {
  switchbool[i] = prefs.getBool(app[i]) ?? false;
}