Skip to main content

Memento - Flutter

  • Memento - Flutter
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'); // Adding a task
taskList.addTask('Study Flutter'); // Adding another task
print('Current tasks: ${taskList.tasks}');

taskList.removeLastTask(); // Removing the last task
final removedTask = taskList.createBackup(); // Saving the removed task
history.addMemento(removedTask); // Storing in history

print('Tasks after removing the last one: ${taskList.tasks}');

// Simulating undoing the task removal
final restoredTask = history.getMemento(); // Retrieving the removed task
if (restoredTask != null) {
taskList.restore(restoredTask); // Restoring the task
}

print('Tasks after undo: ${taskList.tasks}');
}