Running the quiz
- Dart course
- Intermediate
- Lesson 38/116
- 6 min
Learn to ask questions in turn with the run method.
The play method
To run the quiz we write a play method. It prints each question in the list with a number. A for loop iterates the list.
Example: void play() { for (var i = 0; i < questions.length; i++) { print('${i + 1}. ${questions[i].text}'); } }. Here i starts at zero and goes up to questions.length. questions[i] accesses the i-th question.
${i + 1} is string interpolation; it gives the question number. ${questions[i].text} is the question text.
Numbered list output
When play is called each question is printed as 1. What is the capital?. The expression ${i + 1} turns the zero-based index into a one-based number.
With two questions the output is: 1. What is the capital? and 2. How many days in a week?. Each question appears on its own line.
This structure is the foundation of real quiz apps: showing questions in order. The next lesson teaches how to evaluate answers.
Practice Add the play method
Add a void play() method to the Quiz class. The method loops over the questions list with a for loop and prints each question as ${i + 1}. ${questions[i].text}. The main already adds two questions; add the quiz.play() call.
Starter code
class Question {
String text;
String answer;
Question(this.text, this.answer);
}
class Quiz {
List<Question> questions = [];
void addQuestion(Question q) {
questions.add(q);
}
// add the play method: print questions with numbers
}
void main() {
var quiz = Quiz();
quiz.addQuestion(Question('What is the capital?', 'Ankara'));
quiz.addQuestion(Question('How many days in a week?', '7'));
quiz.play();
}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 play() {
for (var i = 0; i < questions.length; i++) {
print('${i + 1}. ${questions[i].text}');
}
}
}
void main() {
var quiz = Quiz();
quiz.addQuestion(Question('What is the capital?', 'Ankara'));
quiz.addQuestion(Question('How many days in a week?', '7'));
quiz.play();
}Expected output
1. What is the capital? 2. How many days in a week?
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The for loop condition
void play() {
for (var i = 0; i < ____.length; i++) {
print('${i + 1}. ${questions[i].text}');
}
}
void play() {
for (var i = 0; i < questions.length; i++) {
print('${i + 1}. ${questions[i].text}');
}
}
Explanation: the loop runs for questions.length iterations.
2 Match the loop parts
| Term | Meaning |
|---|---|
var i = 0 |
Start |
i < questions.length |
Condition |
i++ |
Increment |
questions[i].text |
Question text |
3 What does questions[i] give?
var q = questions[i];- The number of questions
- The i-th Question object Correct answer
- A list
- A number
Explanation: questions[i] gives the i-th Question object in the list.