简体   繁体   中英

How to save multiple bool from list in Flutter with SharedPreferences

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 exactly 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 advice will be wonderful, thanks a lot!

If I could maybe retrieve the data from the value field on the switch with a future void but I haven't seen anywhere any answer...

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM