If the todos.txt file is being created but remains empty, it typically indicates that the saveToFile function is not being called correctly, or the method for writing to the file isn't functioning as expected.
I will provide a code revision that simplifies the saveToFile method to ensure it successfully saves tasks to the file. In addition, we'll add more detailed debugging information to help us identify any issues during the execution.
Here’s another version of the code:
import 'dart:io';
class Todo {
String task;
bool isCompleted;
Todo({
required this.task,
this.isCompleted = false,
});
@override
String toString() {
return '${isCompleted ? '[X]' : '[ ]'} $task';
}
}
class TodoList {
final List<Todo> _todos = [];
void addTask(String task) {
_todos.add(Todo(task: task));
print('Task added: $task');
}
void removeTask(int index) {
if (index < 0 || index >= _todos.length) {
print('Invalid index. Please try again.');
} else {
final removedTask = _todos.removeAt(index);
print('Task removed: ${removedTask.task}');
}
}
void completeTask(int index) {
if (index < 0 || index >= _todos.length) {
print('Invalid index. Please try again.');
} else {
_todos[index].isCompleted = true;
print('Task completed: ${_todos[index].task}');
}
}
void showTasks() {
if (_todos.isEmpty) {
print('No tasks available.');
return;
}
print('To-Do List:');
for (var i = 0; i < _todos.length; i++) {
print('$i: ${_todos[i]}');
}
}
void saveToFile() {
final file = File('todos.txt');
try {
// Using 'writeAsStringSync' to overwrite the file with current tasks
final content = _todos.map((todo) => '${todo.task}|${todo.isCompleted}').join('\n');
file.writeAsStringSync(content);
print('Tasks saved to todos.txt');
} catch (e) {
print('Error saving tasks: $e');
}
}
void loadFromFile() {
final file = File('todos.txt');
try {
if (file.existsSync()) {
final lines = file.readAsLinesSync();
for (var line in lines) {
var parts = line.split('|');
if (parts.length == 2) {
String task = parts[0];
bool isCompleted = parts[1] == 'true';
_todos.add(Todo(task: task, isCompleted: isCompleted));
}
}
print('Tasks loaded from todos.txt');
} else {
print('No saved tasks to load.');
}
} catch (e) {
print('Error loading tasks: $e');
}
}
}
void main() {
final todoList = TodoList();
todoList.loadFromFile(); // Load tasks from a file at the start
while (true) {
print('\nTo-Do List Menu:');
print('1. Add Task');
print('2. Remove Task');
print('3. Complete Task');
print('4. Show Tasks');
print('5. Save Tasks');
print('6. Exit');
stdout.write('Enter your choice: ');
final choice = stdin.readLineSync();
switch (choice) {
case '1':
stdout.write('Enter the task: ');
final task = stdin.readLineSync();
if (task != null && task.isNotEmpty) {
todoList.addTask(task);
} else {
print('Task cannot be empty.');
}
break;
case '2':
stdout.write('Enter the task index to remove: ');
final indexInput = stdin.readLineSync();
if (indexInput != null && int.tryParse(indexInput) != null) {
final index = int.parse(indexInput);
todoList.removeTask(index);
}
break;
case '3':
stdout.write('Enter the task index to complete: ');
final completeIndexInput = stdin.readLineSync();
if (completeIndexInput != null && int.tryParse(completeIndexInput) != null) {
final index = int.parse(completeIndexInput);
todoList.completeTask(index);
}
break;
case '4':
todoList.showTasks();
break;
case '5':
todoList.saveToFile(); // Save tasks before exiting
break;
case '6':
todoList.saveToFile(); // Save tasks before exiting
print('Exiting...');
return;
default:
print('Invalid choice, please select a valid option.');
}
}
}
Key Changes
-
Simplified Saving:
- The
saveToFile method was changed to create a single string with all tasks, formatted as required. This is then written to the file all at once using the writeAsStringSync method.
- This ensures that the file overwrites with the current tasks every time you save.
-
Debug Messages:
- Retained error handling and confirmation print statements to inform the user about the success or failure of save/load operations.
Running the Revised Code
- Ensure you are in a writable directory and that the Dart SDK is properly set up.
- Run the program. Add some tasks using option 1.
- Use option 5 to manually save tasks to
todos.txt.
- Check the contents of
todos.txt — it should now be populated with your tasks.
This should resolve the issue of tasks not saving to the file. If you experience further difficulties, please let me know!