class TaskMemento {
final String task;
TaskMemento(this.task);
}
class TaskList {
List<String> tasks = [];
TaskMemento createBackup() {
return TaskMemento(tasks.last);
}
void restore(TaskMemento memento) {
tasks.add(memento.task);
}
void addTask(String task) {
tasks.add(task);
}
void removeLastTask() {
if (tasks.isNotEmpty) {
tasks.removeLast();
}
}
}
class TaskHistory {
final List<TaskMemento> history = [];
void addMemento(TaskMemento memento) {
history.add(memento);
}
TaskMemento getMemento() {
if (history.isNotEmpty) {
final lastIndex = history.length - 1;
final lastMemento = history[lastIndex];
history.removeLast();
return lastMemento;
}
return null;
}
}
void main() {
final taskList = TaskList();
final history = TaskHistory();
taskList.addTask('Buy milk');
taskList.addTask('Study Flutter');
print('Current tasks: ${taskList.tasks}');
taskList.removeLastTask();
final removedTask = taskList.createBackup();
history.addMemento(removedTask);
print('Tasks after removing the last one: ${taskList.tasks}');
final restoredTask = history.getMemento();
if (restoredTask != null) {
taskList.restore(restoredTask);
}
print('Tasks after undo: ${taskList.tasks}');
}