Adding tasks
- Dart course
- Beginner
- Lesson 84/116
- 6 min
Learn to add tasks with the addTask method.
TodoList and addTask
Now we write a TodoList class that holds Tasks. It will have a List<Task> tasks field and an addTask method. This is the second piece of the project.
The addTask(String title) method creates a new Task and appends it: tasks.add(Task(title));. So calling list.addTask('Read a book') adds one task to the list.
The list starts empty with List<Task> tasks = []. Each call to addTask bumps the list's length by one. This method is the project's core insert operation.
Initializing List<Task>
List<Task> tasks = [] creates an empty list. The type parameter <Task> says the list will only hold Task objects. Trying to add another type yields a compile error.
This safety comes from Dart's type system. You can only append Task objects; a call like tasks.add('text') is rejected. This prevents bugs in the project's later lessons.
Access the list with tasks.length, tasks[i] and similar. Each call to addTask bumps length by one; that is a simple way to confirm the insert worked.
Practice Add the addTask method
Add a void addTask(String title) method to the TodoList class; its body should do tasks.add(Task(title)). Inside main call list.addTask('Kitap oku') and print the count with print(list.tasks.length).
Starter code
class Task {
String title;
bool done = false;
Task(this.title);
}
class TodoList {
List<Task> tasks = [];
// add the addTask method
}
void main() {
var list = TodoList();
// list.addTask('Kitap oku'); and print the count
}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 main() {
var list = TodoList();
list.addTask('Kitap oku');
print(list.tasks.length);
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does addTask do?
- Adds a new Task Correct answer
- Clears the list
- Removes a Task
- Throws
Explanation: addTask appends a new Task to the list.
2 The tasks.add call
class TodoList {
List<Task> tasks = [];
void addTask(String title) {
tasks.____(Task(title));
}
}
class TodoList {
List<Task> tasks = [];
void addTask(String title) {
tasks.add(Task(title));
}
}
Explanation: Dart lists grow with add.
3 Match the List<Task> parts
| Term | Meaning |
|---|---|
List<Task> |
Type |
[] |
Empty init |
tasks.add(...) |
Append |
tasks.length |
Count |