📚 Lesson 2: User Input & Interactivity⏱ 25-30 min📊 Beginner
🎯 Objective
Build an interactive multiple-choice quiz that tests knowledge of Dart programming concepts, accepts user answers, tracks scores, and provides detailed results.
Requirements
Create at least 5 quiz questions about Dart basics
Each question should have 4 multiple choice options (A, B, C, D)
Accept user input for each answer and validate it
Keep track of correct answers count
Display the final score as both count and percentage
╔══════════════════════╗
║ Dart Quiz Game ║
╚══════════════════════╝
Question 1 of 5:
What is the entry point of a Dart program?
A) start()
B) main()
C) init()
D) run()
Your answer (A/B/C/D): B
✅ Correct!
Question 2 of 5:
Which keyword is used for compile-time constants?
A) var
B) final
C) const
D) static
Your answer (A/B/C/D): C
✅ Correct!
[... more questions ...]
╔══════════════════════╗
║ RESULTS ║
╚══════════════════════╝
Score: 4/5 (80%)
Incorrect Questions:
❌ Q3: What does JSON stand for?
Your answer: A | Correct answer: D
📊 Performance: Good job! Keep learning.
Step-by-Step Hints
💡 Hint 1: Data Structure
Use a List<Map<String, dynamic>> to store questions. Each question is a Map with 'question', 'options' (a List), and 'correct' (the answer letter).
💡 Hint 2: Input Validation
Convert user input to uppercase with .toUpperCase(). Check if it's one of 'A', 'B', 'C', 'D' before processing.
import 'dart:io';
void main() {
// Step 1: Define quiz questions
final questions = [
{
'question': 'What is the entry point of a Dart program?',
'options': ['A) start()', 'B) main()', 'C) init()', 'D) run()'],
'correct': 'B',
'explanation': 'Every Dart program starts execution from the main() function.'
},
{
'question': 'Which keyword is used for compile-time constants?',
'options': ['A) var', 'B) final', 'C) const', 'D) static'],
'correct': 'C',
'explanation': 'const creates compile-time constants, while final creates runtime constants.'
},
{
'question': 'What does the \$ sign do in Dart strings?',
'options': ['A) Escape characters', 'B) String interpolation', 'C) End of line', 'D) Start comment'],
'correct': 'B',
'explanation': 'The \$ sign performs string interpolation, inserting variable values into strings.'
},
{
'question': 'Which type represents decimal numbers in Dart?',
'options': ['A) int', 'B) float', 'C) double', 'D) decimal'],
'correct': 'C',
'explanation': 'Dart uses double for floating-point (decimal) numbers.'
},
{
'question': 'What does stdin.readLineSync() return?',
'options': ['A) String', 'B) int', 'C) String?', 'D) void'],
'correct': 'C',
'explanation': 'It returns String? (nullable String) because input could be null.'
},
];
// Step 2: Display header
print('╔══════════════════════╗');
print('║ Dart Quiz Game ║');
print('╚══════════════════════╝\n');
// Step 3: Initialize tracking variables
int score = 0;
List incorrectQuestions = [];
List userAnswers = [];
// Step 4: Loop through questions
for (int i = 0; i < questions.length; i++) {
final q = questions[i];
print('Question ${i + 1} of ${questions.length}:');
print(q['question']);
// Display options
for (var option in (q['options'] as List)) {
print(' $option');
}
// Step 5: Get and validate user answer
String? answer;
bool validAnswer = false;
while (!validAnswer) {
stdout.write('\nYour answer (A/B/C/D): ');
answer = stdin.readLineSync()?.trim().toUpperCase();
if (answer == null || answer.isEmpty) {
print('⚠️ Please enter an answer (A, B, C, or D).');
continue;
}
if (!['A', 'B', 'C', 'D'].contains(answer)) {
print('⚠️ Invalid choice. Please enter A, B, C, or D.');
continue;
}
validAnswer = true;
}
userAnswers.add(answer!);
// Step 6: Check answer
if (answer == q['correct']) {
print('✅ Correct!');
score++;
} else {
print('❌ Wrong! The correct answer was ${q['correct']}.');
print(' ${q['explanation']}');
incorrectQuestions.add(i);
}
print(''); // Blank line between questions
}
// Step 7: Display results
print('╔══════════════════════╗');
print('║ RESULTS ║');
print('╚══════════════════════╝');
double percentage = (score / questions.length) * 100;
print('Score: $score/${questions.length} (${percentage.toStringAsFixed(0)}%)\n');
// Step 8: Show incorrect questions
if (incorrectQuestions.isNotEmpty) {
print('Incorrect Questions:');
for (var index in incorrectQuestions) {
final q = questions[index];
print(' ❌ Q${index + 1}: ${q['question']}');
print(' Your answer: ${userAnswers[index]} | Correct answer: ${q['correct']}');
}
print('');
}
// Step 9: Performance message
print('📊 Performance: ');
if (percentage == 100) {
print('🏆 Perfect score! You\'re a Dart master!');
} else if (percentage >= 80) {
print('🌟 Excellent! You really know your Dart!');
} else if (percentage >= 60) {
print('👍 Good job! Keep learning and practicing.');
} else if (percentage >= 40) {
print('📚 Not bad! Review the lessons and try again.');
} else {
print('💪 Keep studying! You\'ll get better with practice.');
}
// Step 10: Offer retry
stdout.write('\nWould you like to try again? (y/n): ');
String? retry = stdin.readLineSync()?.toLowerCase();
if (retry == 'y' || retry == 'yes') {
print('\nRestarting quiz...\n');
main(); // Restart the quiz
} else {
print('\nThanks for playing! Goodbye! 👋');
}
}