'How to prevent re-saving of previously saved data in Dart Flutter Secure Storage?

I have a code like this:

    void saveList() async {
    final prefences = await SharedPreferences.getInstance();
    List<String> previousList = prefences.getStringList("tests") ?? [];
    prefences.setStringList("tests", previousList + ["English / A1 / Family / Test 1"]);
    setState(() {
    });
    }

I can save any kind of data with this code. It also saves data that has already been recorded before. I want it not to save previously saved data.

In other words, if the data you want to save already exists in the stringList, it should not be saved again.

How can I do that?



Solution 1:[1]

Maybe this would help.

void saveList() async {
  final prefences = await SharedPreferences.getInstance();
  // Check if the list exists
  bool hasList = prefences.containsKey("tests");
  // If yes then
  if (!hasList) {
    prefences.setStringList("tests",  ["new list "]);
 }
else{
  List<String> prevList = prefs.getStringList('tests');
  prefs.setStringList(prevList+['additional list content']);
  }

}

Solution 2:[2]

You can just check it out before saving, like this:

void saveList(String newItem) async {
    final prefences = await SharedPreferences.getInstance();
    List<String> previousList = prefences.getStringList("tests") ?? [];
    if(previousList.contains(newItem))
        return;
    prefences.setStringList("tests", previousList + [newItem]);
    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 nibukdk93
Solution 2 Mahdi Sharifi