Flutter使用localStorage存储含DateTime的Task列表报错如何解决
自定义Task模型持久化异常排查全流程
初始定义的Task类
最初定义的Task模型结构如下:
class Task { Task({this.isDone,this.name,this.time,this.priorityValue}); final String name; bool isDone; final DateTime time; int priorityValue; factory Task.fromJson(Map<String, dynamic> jsonData) { return Task( name: jsonData['name'], isDone: false, time: jsonData['time'], priorityValue: jsonData['priorityValue'], ); } toJSONEncodable() { Map<String, dynamic> m = new Map(); m['name'] = name; m['isDone'] = isDone; m['time'] = time; m['priorityValue'] = priorityValue; return m; } static Map<String, dynamic> toMap(Task task) => { 'name': task.name, 'isDone': task.isDone, 'time': task.time, 'priorityValue': task.priorityValue, }; }
首次存储触发的报错
调用localStorage包持久化Task对象列表时,抛出未处理异常:Unhandled Exception: Converting object to an encodable object failed: Instance of 'DateTime'
对应存储方法代码:
_saveToStorage() { storage.setItem('tasks', list.toJSONEncodable()); print("Saved"); }
第一次修改尝试的问题
最初尝试给time字段直接调用.toString()处理,反而触发新报错:type 'String' is not a subtype of type 'int' of 'index'
后续针对DateTime类型做ISO字符串转换改造,修改了模型的fromJson与toJSONEncodable方法:
factory Task.fromJson(Map<String, dynamic> jsonData) { return Task( name: jsonData['name'], isDone: false, time: jsonData["time"] == null ? null : DateTime.parse(jsonData["time"]), priorityValue: jsonData['priorityValue'], ); } toJSONEncodable() { Map<String, dynamic> m = new Map(); m['name'] = name; m['isDone'] = isDone; m['time'] = time == null ? null : time.toIso8601String(); m['priorityValue'] = priorityValue; return m; } static Map<String, dynamic> toMap(Task task) => { 'name': task.name, 'isDone': task.isDone, 'time': task.time, 'priorityValue': task.priorityValue, };
读取环节的连锁报错
最初读取存储内容的代码逻辑:
var items = storage.getItem('tasks'); if (items != null) { list.items = List<Task>.from( (items as List).map( (item) => Task( name: item['name'], isDone: item['isDone'], time: DateTime.parse(item['time']), priorityValue: items['priorityValue'], ), ), ); }
完成上述模型改造后,读取流程仍然抛出同类报错:type 'String' is not a subtype of type 'int' of 'index'
后续又调整读取逻辑,对获取到的存储内容先做jsonDecode解析,再映射为Task列表:
var items = storage.getItem('tasks'); if (items != null) { final decodedJson = jsonDecode(items); list.items = (decodedJson as List) .map((e) => Task.fromJson(e)) .toList(); final task = list.items.first; print("${task.name}"); }
此时触发新的错误:type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
最终生效的解决方案
最终落地的持久化处理逻辑为:将时间转为字符串存储,获取时间时通过"${selectedDate.toLocal()}".split(' ')[0]转换为字符串格式后再写入存储。
内容的提问来源于stack exchange,提问作者Dahleh
相关产品推荐
相关产品推荐

