SOS video
SOS video

Reputation: 476

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>>'.

Upvotes: 1

Views: 744

Answers (2)

Josteve Adekanbi
Josteve Adekanbi

Reputation: 12673

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(() {});
  }

Upvotes: 1

Silo&#233; Bezerra Bispo
Silo&#233; Bezerra Bispo

Reputation: 2244

As you are using in your list a Map object with primitive types, you can use jsonEncode and convert to a String that can be saved in sharedPreferences and use jsonDecoder when want to revert.

like this:

String toBeSaved = jsonEncode(savedData);
prefs.setString('dataTest', toBeSaved);

Upvotes: 2

Related Questions