CodeBlanks Logo Icon CodeBlanks

Task model

Design the Task class and list structure.

Project: To-do CLI

In this project you will build a to-do CLI. Each lesson adds a piece and the final lesson yields a working app. The first step is the Task class that represents a single task.

A Task has two fields: String title (the task name) and bool done (is it finished?). When a Task is created, done defaults to false. The constructor Task(this.title) sets the title.

Your code will be the foundation for the next lessons. TodoList, addTask, listTasks and completeTask will all use this Task definition. Starting solid matters.

The Task class skeleton

The Task class looks like this: class Task { String title; bool done = false; Task(this.title); }. The title is set by the constructor; done keeps its default false.

Here bool done = false gives the field an initial value. Task(this.title) is the short constructor; it assigns the title parameter straight to the field.

To use the Task write var t = Task('Read a book');. Read the name with t.title and the status with t.done. The next lessons gather these Tasks in a list.

Practice Define the Task class

Define a Task class with String title, bool done = false fields and a Task(this.title) constructor. Inside main create a Task('Kitap oku') instance; print title and done on separate lines.

Starter code

main.dart
void main() {
  // define the Task class (outside main)

  // create an instance and print title and done
}

Sample solution

main.dart
class Task {
  String title;
  bool done = false;
  Task(this.title);
}

void main() {
  var t = Task('Kitap oku');
  print(t.title);
  print(t.done);
}

Expected output

Kitap oku
false

Questions and answers

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

1 Match the Task parts

Term Meaning
String title Task name
bool done Completion flag
Task(this.title) Constructor
false Initial value

2 What is done on a new Task?

  • true
  • null
  • Throws
  • false Correct answer

Explanation: on a new Task done defaults to false.

3 Task constructor

Question
class Task {
  String title;
  bool done = false;
  ____(this.title);
}
Answer
class Task {
  String title;
  bool done = false;
  Task(this.title);
}

Explanation: the constructor shares the class name.

All lessons in Beginner