Stack Overflow Asked by Arthur Adrian on December 13, 2021
I have a Map<Datetime, List> in Dart that stores events needed to fill up a calendar in my Flutter app:
final Map<DateTime, List> _events = {
DateTime(2020, 7, 7): [
{'name': 'Event A', 'isDone': true},
],
DateTime(2020, 7, 11): [
{'name': 'Event A', 'isDone': true}
],
DateTime(2020, 7, 9): [
{'name': 'Event A', 'isDone': true},
{'name': 'Event B', 'isDone': true},
],
DateTime(2020, 7, 10): [
{'name': 'Event A', 'isDone': true},
{'name': 'Event B', 'isDone': true},
],
DateTime(2020, 7, 13): [
{'name': 'Event A', 'isDone': true},
{'name': 'Event B', 'isDone': true},
{'name': 'Event C', 'isDone': false},
],
DateTime(2020, 7, 25): [
{'name': 'Event A', 'isDone': true},
{'name': 'Event B', 'isDone': true},
{'name': 'Event C', 'isDone': false},
],
DateTime(2020, 7, 6): [
{'name': 'Event A', 'isDone': false},
],
};
I want to convert this into JSON but I’m not entirely sure how to model the class. Anyone got any ideas?
If you simply want to convert this to a JSON you can use the jsonEncode
function and use the toEncodable
named parameter to allow your object to be encoded. I made an example here that just cast the keys of your Map
to a String
so that it can be encoded.
jsonEncode(
_events,
toEncodable: (input) {
return _events.map((key, value) {
return MapEntry(key.toString(), value);
});
}
);
When you want to decode this back to your Map<DateTime, List>
you can just do the reverse.
var objectTemp = jsonDecode(
json,
);
var output = objectTemp.map((key, value) {
return MapEntry(DateTime.parse(key), value);
})
Answered by Christopher Moore on December 13, 2021
Create a model class for Event
and store the event data in it (name, isDone and date). Then you put them in a List<Event>
. You can search on this list for a spesific date and get the according events if any. Then you can make that data class serializable.
Answered by easeccy on December 13, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP