简体   繁体   English

如何防止在 Dart Flutter 安全存储中重新保存以前保存的数据?

[英]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.也就是说,如果你要保存的数据已经存在于stringList中,就不要再保存了。

How can I do that?我怎样才能做到这一点?

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

}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM