Dart
Completing tasks
Learn to update task status with completeTask.
The completeTask method
The last method is completeTask: it marks a task as done. It is declared as void completeTask(int i); the i parameter is the task index.
The body is one line: tasks[i].done = true;. This sets the done field of the i-th task to true. When the user finishes a task, its status updates.
Call: list.completeTask(0) — marks the first task as done. This is the project's last core operation. After this we will wire all pieces together.
Checking task status
To read a task's status use tasks[i].done. It returns true or false. You can extend listTasks to show the status too.
Example: print('${tasks[i].title} - ${tasks[i].done}') prints both the name and the status. This makes the CLI more informative.
Later the menu loop will call completeTask; the user enters a number and that task is finished. This comes together in the project's final lesson.
Exercise Add the completeTask method
Add a void completeTask(int i) method to the TodoList class; its body should do tasks[i].done = true. Inside main add list.addTask('Kitap oku') and list.completeTask(0) calls, and print the status with print(list.tasks[0].done).
Show example solution
class Task {
String title;
bool done = false;
Task(this.title);
}
class TodoList {
List<Task> tasks = [];
void addTask(String title) {
tasks.add(Task(title));
}
void listTasks() {
for (var i = 0; i < tasks.length; i++) {
print('${i + 1}. ${tasks[i].title}');
}
}
void completeTask(int i) {
tasks[i].done = true;
}
}
void main() {
var list = TodoList();
list.addTask('Kitap oku');
list.completeTask(0);
print(list.tasks[0].done);
}
Test yourself
-
Match the completeTask parts
- void
- No return
- completeTask
- Method name
- int i
- Index parameter
- tasks[i].done = true
- Assignment
-
What does completeTask(0) do?
- Deletes the first task
- Clears the list
- Marks the first task done
- Throws
Show answer
Marks the first task done — completeTask(0) sets the first task's done to true.
-
The done assignment
void completeTask(int i) {
tasks[i].____ = true;
}
Show answer
void completeTask(int i) {
tasks[i].done = true;
}
Next lesson: Putting it together