Adding questions
- Dart course
- Intermediate
- Lesson 37/116
- 6 min
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.
Practice 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.
Starter code
class Question {
String text;
String answer;
Question(this.text, this.answer);
}
// define the Quiz class: question list and add method
void main() {
// create a Quiz instance, add two questions and print the count
}Sample 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);
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the addQuestion method do?
void addQuestion(Question q) {
questions.add(q);
}- Appends the question to the list Correct answer
- Prints the question
- Removes a question from the list
- Modifies the question
Explanation: addQuestion appends the given question to the list.
2 The questions.add call
class Quiz {
List<Question> questions = [];
void addQuestion(Question q) {
____.add(q);
}
}
class Quiz {
List<Question> questions = [];
void addQuestion(Question q) {
questions.add(q);
}
}
Explanation: questions.add(q) appends the element.
3 Match the Quiz parts
| Term | Meaning |
|---|---|
List<Question> |
Question list type |
questions = [] |
Empty start |
addQuestion(Question q) |
Add method |
questions.add(q) |
Append to list |