本地存储:将Map <string,string>添加到存储的List </string,string>

时间:2014-12-28 10:18:07

标签: dart local-storage

我正在尝试使用本地存储来存储任务。

这是我的功能:

void saveTask(_) {
    String sum = querySelector('#tsummary').value;
    String con = querySelector('#tcontent').value;
    String sched = querySelector('#dateinp').value;
    String timestamp = new DateTime.now().millisecondsSinceEpoch.toString();
    Storage localStorage = window.localStorage;
    var dt = localStorage['darttasks'];

    if (dt == null) {
    localStorage['darttasks'] = JSON.encode([]);
    }
    var task = {"summary":sum, "content" :con,"scheduled":sched, "id":timestamp};
    localStorage['darttasks'] = JSON.encode(JSON.decode(localStorage['darttasks']).add(task));
}

但是,这会失败,并显示以下错误消息:

异常:null对象没有方法'add'。

  

NoSuchMethodError:找不到方法:'add'Receiver:null参数:   ['_LinkedHashMap'的实例]

我做错了什么?

提前致谢。

1 个答案:

答案 0 :(得分:3)

问题是你的最后一行代码void。列表的.add函数返回void。这是一个更新版本:

final String STORAGE_KEY = 'darttasks';
List tasks = [];
if(window.localStorage.containsKey(STORAGE_KEY)) {
  tasks = JSON.decode(window.localStorage[STORAGE_KEY]);

  // Decoding Error, should not happen
  if(tasks == null) {
    tasks = [];
  }
}

var task = {
  "summary": sum,
  "content": con,
  "scheduled": sched,
  "id": timestamp
};
tasks.add(task);
window.localStorage[STORAGE_KEY] = JSON.encode(tasks);