Map<DateTime, List<CleanCalendarEvent>> events = {};
example:
DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day): [
CleanCalendarEvent('Event A',
startTime: DateTime(DateTime.now().year, DateTime.now().month,
DateTime.now().day, 10, 0),
endTime: DateTime(DateTime.now().year, DateTime.now().month,
DateTime.now().day, 12, 0),
description: 'A special event',
color: Colors.orangeAccent),
],
DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day + 2):
[
CleanCalendarEvent('Event B',
startTime: DateTime(DateTime.now().year, DateTime.now().month,
DateTime.now().day + 2, 10, 0),
endTime: DateTime(DateTime.now().year, DateTime.now().month,
DateTime.now().day + 2, 12, 0),
color: Colors.orange),
CleanCalendarEvent('Event C',
startTime: DateTime(DateTime.now().year, DateTime.now().month,
DateTime.now().day + 2, 14, 30),
endTime: DateTime(DateTime.now().year, DateTime.now().month,
DateTime.now().day + 2, 17, 0),
color: Colors.pink),
],
}
在这个Map中,我想检查我获取的Date时间对象是否已经存在。如果是,那么将CleanCalendarEvent添加到映射中特定DateTime对象的列表中。如果没有,则添加一个新的DateTime和List键值对。
这是我的方法,但它不工作
if (events.containsKey(DateTime(date2.year, date2.month, date2.day))) {
events[DateTime(date2.year, date2.month, date2.day)]!.add(
CleanCalendarEvent('BookingText',
startTime: DateTime(now.year, now.month, now.day + 1, 10, 0),
endTime: DateTime(now.year, now.month, now.day + 1, 12, 0),
description: 'A special event',
color: Colors.orangeAccent));
} else {
events[DateTime(date2.year, date2.month, date2.day)] = [
CleanCalendarEvent('BookingText',
startTime: DateTime(now.year, now.month, now.day + 1, 10, 0),
endTime: DateTime(now.year, now.month, now.day + 1, 12, 0),
description: 'A special event',
color: Colors.orangeAccent)
];
}
这在dartpad中工作-我采用了您的代码并简化了一点。不知道你哪里出了问题。
Map<DateTime, List<String>> events = {};
void addMapValue(DateTime d, String value) {
if (events.containsKey(d)) {
events[d]!.add(value);
} else {
events[d] = [value];
}
}
void main() {
events[DateTime(2022,6,20)]=['a'];
events[DateTime(2022,6,21)]=['b'];
events[DateTime(2022,6,22)]=['c'];
addMapValue(DateTime(2022,6,20), 'x');
addMapValue(DateTime(2022,6,30), 'y');
print(events);
}
输出是:
{
2022-06-20 00:00:00.000: [a, x],
2022-06-21 00:00:00.000: [b],
2022-06-22 00:00:00.000: [c],
2022-06-30 00:00:00.000: [y]
}
答案,而不是传递DateTime的新对象现在我传递日期
if (events.containsKey(date2)) {
events[date2]!.add(CleanCalendarEvent('BookingText',
startTime: DateTime(now.year, now.month, now.day + 1, 10, 0),
endTime: DateTime(now.year, now.month, now.day + 1, 12, 0),
description: 'A special event',
color: Colors.orangeAccent));
} else {
events[date2] = [
CleanCalendarEvent('BookingText',
startTime: DateTime(now.year, now.month, now.day + 1, 10, 0),
endTime: DateTime(now.year, now.month, now.day + 1, 12, 0),
description: 'A special event',
color: Colors.orangeAccent)
];
}