【问题标题】:Flutter - how to store a list in GetStorage?Flutter - 如何在 GetStorage 中存储列表?
【发布时间】:2021-12-29 03:45:27
【问题描述】:

对于用户浏览的每篇文章,我都想保存 ID 信息。 我正在使用getstorage,我的代码示例如下。

我也找不到真正的方法,我正在寻找保存 id 列表的最佳方法。

    final box = GetStorage();
  List<String> myFavoriteList = [];

  saveFav(String id) {
    myFavoriteList.add(id);
    box.write('favoriteArticles', myFavoriteList.cast<String>());
  }

  ifExistInFav(String id) async {
    bool ifExists = false;
    List<String> my = (box.read('favoriteArticles').cast<String>() ?? []);
    ifExists = my.contains(id) ? true : false;
    return ifExists;
  }

【问题讨论】:

    标签: list flutter sharedpreferences


    【解决方案1】:

    首先,您需要定义您的列表并将其转换为字符串。

    ** 请注意,如果您使用自定义数据类型,请确保将模型转换为字符串。

    那么您可以使用以下内容将 List 存储为 String 对象

    final box = GetStorage('AppNameStorage');
    /// write a storage key's value
    saveListWithGetStorage(String storageKey, List<dynamic> storageValue) async => await box.write(key: storageKey, value: jsonEncode(storageValue));
    /// read from storage
    readWithGetStorage(String storageKey) => box.read(storageKey);
    

    保存过程的实现:

    saveList(List<dynamic> listNeedToSave) {
        /// getting all saved data
        String oldSavedData = GetStorageServices().readWithGetStorage('saveList');
    
    /// in case there is saved data
    if(oldSavedData != null){
      /// create a holder list for the old data
      List<dynamic> oldSavedList = jsonDecode(oldSavedData);
      
      /// append the new list to saved one
      oldSavedList.addAll(listNeedToSave);
      /// save the new collection
      return GetStorageServices().saveListWithGetStorage('saveList', oldSavedList);
    } else{
      /// in case of there is no saved data -- add the new list to storage
      return GetStorageServices().saveListWithGetStorage('saveList', listNeedToSave);
    }
    }
    
    
    /// read from the storage
    readList() => GetStorageServices().readWithGetStorage('saveList');
    

    然后是用法:

    onTap: () async => print('\n\n\n read list items ${jsonDecode(await readList())}\n\n\n'),
    

    【讨论】:

    • 你好,我想使用getstorage而不是flutter_secure_storage
    • 糟糕,我的错,我用正确的 sn-p 更新
    • 方法 readWithGetStorage 没有定义。这是什么方法?
    • 请重新检查我已经更新了答案
    • readWithGetStorage() 这个方法返回最后添加的字符串。
    猜你喜欢
    • 2021-06-28
    • 2021-10-01
    • 2020-10-17
    • 1970-01-01
    • 2021-09-16
    • 2020-06-01
    • 1970-01-01
    • 2023-02-12
    • 1970-01-01
    相关资源
    最近更新 更多