Dart
Adding questions
Learn to add questions with the addQuestion method.
Quiz class and addQuestion
Now let's write the Quiz class that stores questions. It has a List<Question> field and an addQuestion method. Each added question grows the list.
Example: class Quiz { List<Question> questions = []; void addQuestion(Question q) { questions.add(q); } }. Here questions starts as an empty list. The addQuestion method takes a Question parameter and appends it.
With this design you can add as many questions as you want. The next lessons will iterate the list to show questions.
Initializing List<Question>
The line List<Question> questions = []; creates an empty Question list. In Dart [] means an empty list. Because the type is Question, only Question objects can be added.
This gives type safety: questions.add('text') is a compile error because 'text' is not a Question. Only questions.add(Question(...)) is valid.
Read the list length with questions.length. It tells you how many elements are stored.
Exercise Add the Quiz class and addQuestion
The Question class is already defined. Now define a Quiz class with a List<Question> questions = [] field and a void addQuestion(Question q) method. Inside the method write questions.add(q). In main create a Quiz, add two questions and print quiz.questions.length.
Show example solution
class Question {
String text;
String answer;
Question(this.text, this.answer);
}
class Quiz {
List<Question> questions = [];
void addQuestion(Question q) {
questions.add(q);
}
}
void main() {
var quiz = Quiz();
quiz.addQuestion(Question('What is the capital?', 'Ankara'));
quiz.addQuestion(Question('How many days in a week?', '7'));
print(quiz.questions.length);
}
Test yourself
-
What does the addQuestion method do?
void addQuestion(Question q) {
questions.add(q);
}
- Appends the question to the list
- Prints the question
- Removes a question from the list
- Modifies the question
Show answer
Appends the question to the list — addQuestion appends the given question to the list.
-
The questions.add call
class Quiz {
List<Question> questions = [];
void addQuestion(Question q) {
____.add(q);
}
}
Show answer
class Quiz {
List<Question> questions = [];
void addQuestion(Question q) {
questions.add(q);
}
}
-
Match the Quiz parts
- List<Question>
- Question list type
- questions = []
- Empty start
- addQuestion(Question q)
- Add method
- questions.add(q)
- Append to list
Next lesson: Running the quiz