'How to store list of string with sharedpreferences in Flutter?

I've a list of string that I've insert into a ListView in Flutter:

How can I store the list with sharedPreferences and use it in the ListView?



Solution 1:[1]

Declare your variables

List<Todo> list = new List<Todo>();
SharedPreferences sharedPreferences;

Save data into SharedPreferences after converting to json

void saveData(){
  List<String> stringList = list.map(
    (item) => json.encode(item.toMap()
  )).toList();
  sharedPreferences.setStringList('list', stringList);
}

Load data from SharedPreferences and convert back

void loadData() {
  List<String> listString = sharedPreferences.getStringList('list');
  if(listString != null){
    list = listString.map(
      (item) => Todo.fromMap(json.decode(item))
    ).toList();
    setState((){});
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 João Soares