Home > front end >  How to prevent re-saving of previously saved data in Dart Flutter Secure Storage?
How to prevent re-saving of previously saved data in Dart Flutter Secure Storage?

Time:03-06

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?

CodePudding user response:

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']);
  }

}

CodePudding user response:

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