CodeBlanks Logo Icon CodeBlanks

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.

Practice 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).

Starter code

main.dart
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}');
    }
  }
  // add the completeTask method
}

void main() {
  var list = TodoList();
  list.addTask('Kitap oku');
  // completeTask and status print
}

Sample solution

main.dart
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);
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the completeTask parts

Term Meaning
void No return
completeTask Method name
int i Index parameter
tasks[i].done = true Assignment

2 What does completeTask(0) do?

  • Deletes the first task
  • Clears the list
  • Marks the first task done Correct answer
  • Throws

Explanation: completeTask(0) sets the first task's done to true.

3 The done assignment

Question
void completeTask(int i) {
  tasks[i].____ = true;
}
Answer
void completeTask(int i) {
  tasks[i].done = true;
}

Explanation: the done field is set to true.

All lessons in Beginner