Listing tasks
- Dart course
- Beginner
- Lesson 85/116
- 6 min
Learn to print tasks formatted with listTasks.
The listTasks method
Now we add a listTasks method to the TodoList. It prints every task numbered, so the user can see what is in the list.
The method is declared as void listTasks(). Inside, a for loop walks the tasks list and prints each task with print.
Example: for (var i = 0; i < tasks.length; i++) { print(tasks[i].title); }. This prints only the title of each task. You can also add the index or status; the task in this lesson will ask for the index.
Numbered list
To print tasks numbered, use the loop index. Example: print('${i + 1}. ${tasks[i].title}'). This yields output like '1. Read a book'.
String interpolation puts expressions inside ${...}. i + 1 starts the count at 1; programmers count from 0, so we add 1 to show users '1, 2, 3'.
This small touch makes the list readable. Later we can add the completion status; but first the bare list matters.
Practice Add the listTasks method
Add a void listTasks() method to the TodoList class. Inside, loop over tasks with a for loop and print each task as '${i + 1}. ${tasks[i].title}' with print. Inside main add list.addTask('Kitap oku') and list.listTasks() calls.
Starter code
class Task {
String title;
bool done = false;
Task(this.title);
}
class TodoList {
List<Task> tasks = [];
void addTask(String title) {
tasks.add(Task(title));
}
// add the listTasks method
}
void main() {
var list = TodoList();
list.addTask('Kitap oku');
// add a listing call
}Sample 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 main() {
var list = TodoList();
list.addTask('Kitap oku');
list.listTasks();
}Expected output
1. Kitap oku
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The for loop
void listTasks() {
for (var i = 0; i < tasks.____; i++) {
print(tasks[i].title);
}
}
void listTasks() {
for (var i = 0; i < tasks.length; i++) {
print(tasks[i].title);
}
}
Explanation: the list length is read with length.
2 Match the loop parts
| Term | Meaning |
|---|---|
for |
Loop keyword |
var i = 0 |
Init |
i < tasks.length |
Condition |
i++ |
Step |
3 What does tasks[i] return?
- The first Task
- The Task at index i Correct answer
- Throws
- The list length
Explanation: tasks[i] returns the Task at index i.