I have a Model of 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,
};
}
and When using the localStorage package to save some list of objects I got this error =>
(Flutter) Unhandled Exception: Converting object to an encodable object failed: Instance of 'DateTime'
_saveToStorage() {
storage.setItem('tasks', list.toJSONEncodable());
print("Saved");
}
i tried to use .toString() but then i get this error => type 'String' is not a subtype of type 'int' of 'index'
any Idea to save Datetime on LocalStorage package?
Update:
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'],
),
),
);
}
after the update i got this error "type 'String' is not a subtype of type 'int' of 'index'"
Update2:
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}");
// 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'],
// ),
// ),
// );
}
fter the second update i got "type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'"
Fixed
i changed the DaeTme toa String in the model and convert the time to a string when got it by
"${selectedDate.toLocal()}".split(' ')[0]