CodeBlanks Logo Icon CodeBlanks

Quiz model

Design the skeleton of Question and Quiz classes.

Project: Quiz app

In this project you will build a quiz app. Each lesson adds a piece and the final lesson yields a working mini app. The first step is the Question class that represents a single question.

A Question has two fields: String text (the question) and String answer (the correct answer). The constructor Question(this.text, this.answer) sets both fields.

In the next lessons we will gather these Question objects in a list and run the quiz. Starting with a solid model matters.

The Question class skeleton

The Question class looks like this: class Question { String text; String answer; Question(this.text, this.answer); }. The text and answer constructor parameters are assigned straight to the fields.

Here this.text assigns the parameter text to the field text. The same goes for answer. This is called the constructor parameter shorthand.

To use the Question write var q = Question('What is the capital?', 'Ankara');. Read the question with q.text and the answer with q.answer.

Practice Define the Question class

Define a Question class with String text and String answer fields and a Question(this.text, this.answer) constructor. Inside main create a Question('What is the capital?', 'Ankara') instance; print text and answer on separate lines.

Starter code

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

  // create an instance and print text and answer
}

Sample solution

main.dart
class Question {
  String text;
  String answer;
  Question(this.text, this.answer);
}

void main() {
  var q = Question('What is the capital?', 'Ankara');
  print(q.text);
  print(q.answer);
}

Expected output

What is the capital?
Ankara

Questions and answers

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

1 Match the Question parts

Term Meaning
String text Question text
String answer Correct answer
Question(this.text, this.answer) Constructor
text, answer Two parameters

2 How many fields does the Question class have?

  • 1
  • 4
  • 3
  • 2 Correct answer

Explanation: the Question class has two fields: text and answer.

3 Question constructor

Question
class Question {
  String text;
  String answer;
  ____(this.text, this.answer);
}
Answer
class Question {
  String text;
  String answer;
  Question(this.text, this.answer);
}

Explanation: the constructor shares the class name.

All lessons in Intermediate