Learn how to implement quiz logic in Flutter using functions and conditions to handle questions, capture answers, and update scores.
Welcome to the exciting world of coding your very own quiz app! In this section, we’ll dive into the logic that powers a quiz, teaching you how to display questions, capture user answers, check for correctness, and update scores. By the end of this lesson, you’ll have a working quiz app that you can customize and share with friends and family.
Before we jump into coding, let’s break down what quiz logic involves:
To implement this logic, we’ll use functions and conditions. Functions will help us organize our code into reusable blocks, while conditions will allow us to make decisions based on user input.
We’ll create a function that displays each question along with its possible answers. This function will be called every time we need to show a new question.
Another function will handle the logic of checking if the user’s selected answer is correct. This function will also update the score and provide feedback.
We’ll keep track of the user’s score and update it whenever they answer a question correctly.
Let’s look at the code that brings all these concepts together:
import 'package:flutter/material.dart';
void main() {
runApp(QuizApp());
}
class QuizApp extends StatefulWidget {
@override
_QuizAppState createState() => _QuizAppState();
}
class _QuizAppState extends State<QuizApp> {
final List<Map<String, dynamic>> questions = [
{
'question': 'What is the capital of France?',
'answers': ['Berlin', 'London', 'Paris', 'Rome'],
'correct': 'Paris',
},
{
'question': 'Which planet is known as the Red Planet?',
'answers': ['Earth', 'Mars', 'Jupiter', 'Saturn'],
'correct': 'Mars',
},
];
int currentQuestion = 0;
int score = 0;
String feedback = '';
void answerQuestion(String selected) {
if (selected == questions[currentQuestion]['correct']) {
score++;
feedback = 'Correct!';
} else {
feedback = 'Wrong! The correct answer was ${questions[currentQuestion]['correct']}.';
}
setState(() {
if (currentQuestion < questions.length - 1) {
currentQuestion++;
} else {
feedback += ' Your final score is $score out of ${questions.length}.';
}
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Simple Quiz App'),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
Text(
questions[currentQuestion]['question'],
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
...questions[currentQuestion]['answers'].map<Widget>((answer) {
return ElevatedButton(
onPressed: () => answerQuestion(answer),
child: Text(answer),
);
}).toList(),
SizedBox(height: 20),
Text(
feedback,
style: TextStyle(fontSize: 18, color: Colors.blue),
),
],
),
),
),
);
}
}
StatefulWidget
to manage the state of our quiz app, allowing us to update the UI when the user answers a question.answerQuestion
function checks if the selected answer is correct, updates the score, and provides feedback.setState
to update the UI with the next question or final score.Now it’s your turn! Add more questions to the quiz or modify existing ones to better suit your interests. You can change the questions, answers, or even the feedback messages.
To help you understand the flow of the quiz logic, here’s a diagram:
flowchart TD A[Start Quiz] --> B[Display Question] B --> C[User Selects Answer] C --> D{Is Answer Correct?} D -- Yes --> E[Increment Score] D -- No --> F[Show Correct Answer] E --> G[Next Question] F --> G G --> H{More Questions?} H -- Yes --> B H -- No --> I[End Quiz and Show Score]
Coding a quiz app is a fantastic way to practice problem-solving and creativity. Test your quiz with friends or family and gather feedback to improve it. Remember, coding is all about learning and having fun!