Search code examples
flutterdartsharedpreferences

How to save a list to shared preferences


I want to save a list to shared preferences, but it doesn't work... The goal is to add data to the variable and save it.

This is the variable I want to save:

    var savedData = [
      {'date': 0, 'testNumber': 0},
    ];

And this is the code I tried for saving and receiving the variable:

 Future<void> saveDataTest() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setStringList(
        'dataTest', savedData.map((i) => i.toString()).toList());
  }
    
 Future<String> getDataStringTest() async {
    final prefs = await SharedPreferences.getInstance();
    savedData =
     prefs.getStringList('dataTest').map((i) => int.parse(i)).toList();
    setState(() {});
  }

This is the error I get:

A value of type 'List<int>' can't be assigned to a variable of type 'List<Map<String, int>>'.
Try changing the type of the variable, or casting the right-hand type to 'List<Map<String, int>>'.

Solution

  • Try using jsonEncode and jsonDecode from import 'dart:convert';

    Like so:

    
     Future<void> saveDataTest() async {
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString("dataTest ", jsonEncode(savedData));
      }
        
     Future<String> getDataStringTest() async {
        final prefs = await SharedPreferences.getInstance();
        savedData = List.from(jsonDecode(prefs.getString("dataTest")));
        setState(() {});
      }